Search code examples
carraysinputreadfilegetline

Reading line by line in C and storing to array


enter image description here

Im trying to read a text file with inputs in the above format. Im able to read each line with this code:

FILE *file = fopen(argv[1], "r");
...

char * line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, file)) != -1)

so that "line" is equal to each line in the file and if i output what is read for ex: i get the first output as "1 2 3 4 5 6 7 8 9". How can i store these numbers to a 2d array ?. how can i split at each space and get the number only ?


Solution

  • Sample using sscanf

    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[]) {
        int numbers[9][9];
        FILE *file = fopen(argv[1], "r");
        char * line = NULL;
        size_t len = 0;
        ssize_t read;
        int rows = 0;
        while ((read = getline(&line, &len, file)) != -1){
            int *a = numbers[rows];
            if(9 != sscanf(line, "%d%d%d%d%d%d%d%d%d", a, a+1, a+2,a+3,a+4,a+5,a+6,a+7,a+8)){
                fprintf(stderr, "%s invalid format at input file\n", line);
                return EXIT_FAILURE;
            }
            if(++rows == 9)
                break;
        }
        fclose(file);
        free(line);
        //check print
        for(int r = 0; r < 9; ++r){
            for(int c = 0; c < 9; ++c)
                printf("%d ", numbers[r][c]);
            puts("");
        }
    }