Search code examples
cfile-iozero

Read numbers from sscanf are 0


Good day to the community. The code I am trying to write must should read integers from a file while skipping lines that start with #. My problem is that no numbers are read and instead the it returns 0. The file looks like this:

#hello
#myname
#is
#file
122 4838
112   393949
1239 233
29393 44949
3 2
445 566

The output is:

0       0
Read 0 numbers
0       0
Read 0 numbers
0       0
Read 0 numbers
0       0
Read 0 numbers 

The code is:

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

typedef struct {
    int start;
    int end;
} path;
int main()
{
    int test; 
    path* array=malloc(sizeof(path));
    if(array==NULL) {
        printf("Error allocating memory\n");
        abort();
    }


    FILE* fd=fopen("Test.txt","r");
    if(fd==NULL) {
        printf("Error opening file\n");
        abort();
    }
    char buff[200];
    int counter=0;

    char c;
    while(fgets(buff,200,fd)&&counter<6) {
        c=buff[0];
        if(c=="#") {
            continue;
        }
        test=sscanf(&buff,"%d%d",array[counter].start,array[counter].end);
        printf("%d\t%d\n",array[counter].start,array[counter].end);
        printf("Read %d numbers\n", test);
        counter++;
    }

    fclose(fd);
    free(array);
    return 0;
}

Solution

  • The problem in your code is in your arguments to the sscanf function. This requires the addresses of all variables that are the 'targets' for corresponding format fields (but reading in char[] strings is different, as the array name will decay to a pointer when used as a function argument).

    So, in your case, to read in the two integer structure members, you should use this:

    test = sscanf(buff, "%d%d", &array[counter].start, &array[counter].end);
    

    Note 1: Also, you don't need the & operator on the buff argument, as this will decay, as mentioned above!

    Note 2: Because the . (structure-member access operator) has a higher precedence than the & (address-of operator), the expression &array[counter].start is the same as &(array[counter].start) - but you may prefer the latter, more explicit code, as this can make things clearer for others to read and understand.

    Feel free to ask for further clarification and/or explanation.