简体   繁体   中英

Reading in data from a file into an array

If I have an options file along the lines of this:

size = 4
data = 1100010100110010

And I have a 2d size * size array that I want to populate the values in data into, what's the best way of doing it?

To clarify, for the example I have I'd want an array like this:

int[4][4] array = {{1,1,0,0}, {0,1,0,1}, {0,0,1,1}, {0,0,1,0}}. (Not real code but you get the idea).

Size can be really be any number though.

I'm thinking I'd have to read in the size, maloc an array and then maybe read in a string full of data then loop through each char in the data, cast it to an int and stick it in the appropriate index? But I really have no idea how to go about it, have been searching for a while with no luck.

Any help would be cool! :)

Loops.

FILE *fp = fopen("waaa.txt", "r");
if(fp == null) { /* bleh */ return; }

int j = 0;
while(char ch = fgetc(fp)) {
    for(int i = 0; i < 4; ++i) {
        array[j][i] = ch;
    }
    ++j;
}

I am not sure with the fgetc() syntax.. Just check on it. It reads one character at a time.

int process_file(int **array, char const *file_name)
{
    int size = 0;
    FILE *file = fopen(file_name, "rt");
    if(fp == null)
        return -1;//can't open file
    char line[1024]; //1024 just for example
    if(fgets(line, 1024, file) != 0)
    {
        if(strncmp(line, "size = ", 7) != 0)
        {
            fcloes(file);
            return -2; //incorrect format
        }
        size = atoi(line + 7);
        array = new int * [size];
        for(int i = 0; i < size; ++i)
            array[i] = new int [size];
    }
    else
    {
        fclose(file);
        return -2;//incorrect format
    }
    if(fgets(line, 1024, file) != 0)
    {
        if(strncmp(line, "data = ", 7) != 0)
        {
            fcloes(file);
            for(int i = 0; i < size; ++i)
                delete [] array[i];
            delete [] array;
            return -2; //incorrect format
        }
        for(int i = 7; line[i] != '\n' || line[i] != '\0'; ++i)
            array[(i - 7) / size][(i - 7) % size] = line[i] - '0';
    }
    else
    {
        fclose(file);
        for(int i = 0; i < size; ++i)
            delete [] array[i];
        delete [] array;
        return -2; //incorrect format
    }
    return 0;
}

Don't forget delete array before program ends;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM