Home > Mobile >  Read integers values from a file in c
Read integers values from a file in c

Time:10-24

I want to read a simple data file, where the columns are separeted by a TAB.

P   C   D
4   1   4
5   2   5
20  4   20
...

I'm trying to do like this:

FILE *file_ptr = fopen(system_file, "r");
if (file_ptr == NULL) {
    printf("no such file.\n");
    return 0;
}

for (int i = 0; i < N_LINES; i  ){
    fscanf(file_ptr, "%d %d %d ", &system.tasks[i].p, &system.tasks[i].c, &system.tasks[i].d);
}

But when i print the values from system.tasks it always returns 0 for all.

CodePudding user response:

You cannot tell what is happening because you do not test the return value of fscanf() so you do not know where the parsing fails.

You properly test for fopen failure, but you should provide a meaningful error message.

Furthermore, parsing a file with fscanf() is error prone because white space skipped when parsing numbers and strings may include line breaks.

It is much more reliable to read the file one line at a time with fgets() and parse the line with sscanf() (or other more precise functions such as strtol). Testing the return value of sscanf() is very important to detect invalid contents and prevent subsequent undefined behavior as the destination variables will not have been updated.

Here is a modified version using fgets() to read one line at a time:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct task {
    int p, c, d;
    //...
};

#define N_LINES 100
struct system {
    struct task tasks[N_LINES];
    //...
} system;

int main() {
    char buf[256];
    const char *system_file = "system.txt";
    FILE *file_ptr = fopen(system_file, "r");
    if (file_ptr == NULL) {
        fprintf(stderr, "cannot open %s: %s\n", system_file, strerror(errno));

    int line = 0;
    // skip the header line
    fgets(buf, sizeof buf, file_ptr);
    line  ;
    // parse the file contents
    for (int i = 0; i < N_LINES;) {
        line  ;
        if (!fgets(buf, sizeof buf, file_ptr)) {
            fprintf(stderr, "%s:%d: missing records\n",
                    system_file, line);
            break;
        }
        if (sscanf(buf, "%d%d%d", &system.tasks[i].p,
                   &system.tasks[i].c, &system.tasks[i].d) == 3) {
            i  ;
        } else {
            fprintf(stderr, "%s:%d: invalid format: %s", 
                    system_file, line, buf);
        } 
    }
    fclose(file_ptr);
    //...
    return 0;
}
  •  Tags:  
  • c
  • Related