1

I am reading a file containing characters and a lot of integers. I am reading it using the fscanf function in order to retrieve all the integers. However I don't know in advance how many integers there will be on a line. How could I still make it work?

The issue is that to use the easy function fscanf I have to know in advance what structure my file will have, i.e. how many integers etc...

I d like to use something like:

fscanf(fp, "%d//%d %d//%d", &array1[0], &array1[1], &array1[3], &array1[4]);

e.g.: this is my file

f 7//1 8//1 10//1 9//1

f 9//2 10//2 12//2 11//2

f 11//3 12//3 14//3 13//3

f 21//8 22//8 24//8 23//8

f 23//9 24//9 26//9 25//9

f 25//10 26//10 28//10 27//10

f 65//30 66//30 68//30 67//30

f 10//31 8//31 70//31 68//31 66//31 64//31 62//31 60//31 58//31 56//31 54//31 52//31 50//31 48//31 46//31 44//31 42//31 40//31 38//31 36//31 34//31 32//31 30//31 28//31 26//31 24//31 22//31 20//31 18//31 16//31 14//31 12//31

f 67//32 68//32 70//32 69//32
J.Doe
  • 77
  • 7

1 Answers1

1

You don't use fscanf to read file by lines. What you can do is to read lines using fgets and then process them using strtok and sscanf.

int read_n, value;
char line[SIZE], *val;
char delims[] = " //\r\n\t ";

while (fgets(line, size, file) != NULL)
{
    val = strtok(line, delims);
    read_n = sscanf(val, "%d", &value);

    while(read_n > 0)
    {
        printf("Read [%d]\n", value);
        val = strtok(NULL, delims);
        read_n = (val == NULL) ? 0 : sscanf(val, "%d",&value);
    }
}

Use strtok_r in multithreaded environment.

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • @J.Doe There is undefined behaviour in your code from the link. Let me fix this for you in a minute. – 4pie0 Apr 09 '16 at 13:34
  • @J.Doe Please find working example [here](https://github.com/spinlockirqsave/c/tree/master/io/fgets_strtok_sscanf_file). – 4pie0 Apr 09 '16 at 14:43