Dronacharya
Dronacharya

Reputation: 481

Reading a .txt file into a 2-d array

I have a text file as follows:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20

I want to read into a 2-d array of integers. The problem is the file provides no information about the dimensions of the 2-d data. I tried doing it as follows:

FILE *input_file = fopen(argv[1], "r");
while (! feof(input_file)) {
    read = fscanf(input_file, "%d%c", &x, &del);
    if (read != 2) {
        i--;
        break;
    }
    in_data[i][j] = x;
    if ( del == '\n') {
        i++;
        j =0;
        continue;
    }
    j++;
}

This code works fine if the character after the last data-item in a line is a newline, but fails otherwise. What is the reliable way to read 2-d data from a file without knowing the dimensions of the data beforehand?

Upvotes: 0

Views: 219

Answers (1)

paddy
paddy

Reputation: 63471

A simple approach is to use fgets to read a line at a time. You can then use strtol to read the values out. Make use of the endptr pointer it sets so you can read the next value.

Alternatively you can make a short function to eat whitespace by reading a character at a time. You can handle newlines in there. Read until you encounter a non-whitespace and then put that character back into the stream using ungetc. Something like this:

// Returns false if EOF or error encountered.
int eat_whitespace( FILE *fp, int *bNewLineEncountered )
{
    int c;
    *bNewLineEncountered = 0;

    while( EOF != (c = fgetc(fp)) ) {
        if( c == '\n' ) {
            *bNewLineEncountered = 1;
        } else if( !isspace(c) ) {
            ungetc(c, fp);
            break;
        }
    }

    return (c != EOF);
}

Upvotes: 1

Related Questions