Home > OS >  Reading from a file line by line and word by word in C
Reading from a file line by line and word by word in C

Time:12-26

I have to read from a file and store the data in a structure.(You can see the structure below) Each line consists of 5 integers and 1 char variable. Each line must be an index of the "structure line".

struct line {
    int lineno;
    int x1;
    int y1;
    int x2;
    int y2;
    char color;
    int next;
};

struct line memorybuffer[25];

For example in this file:

1 10 10 50 60 R
3 80 10 10 10 B
4 40 20 40 0 Y

I should get:

memorybuffer[0].lineno = 1;
memorybuffer[0].x1 = 10;
memorybuffer[1].lineno = 3;

I could not find how can I read the data (integer char) line by line and word by word, and store it in the line structure.

Could you please help me to find the way? Thanks a lot.

CodePudding user response:

I could not find how can I read the data

Please read the man page for fscanf, which can address your needs completely.

CodePudding user response:

As hinted by Shawn you can read the file one line at a time with fgets() and parse it with sscanf():

#include <stdio.h>

struct line {
    int lineno;
    int x1;
    int y1;
    int x2;
    int y2;
    char color;
    int next;
};

struct line memorybuffer[25];

int main() {
    char line[256];
    int i;

    for (i = 0; i < 25 && fgets(line, sizeof line, stdin);) {
        if (sscanf("%d %d %d %d %d %c\n",
                   &memorybuffer[i].lineno,
                   &memorybuffer[i].x1,
                   &memorybuffer[i].y1,
                   &memorybuffer[i].x2,
                   &memorybuffer[i].y2,
                   &memorybuffer[i].color) == 6) {
            /* record was parsed correctly */
            i  ;
        } else {
            printf("invalid format: %s", line);
        }
    }
    ...
    return 0;
}
  • Related