Search code examples
ccompiler-errorsscanffopenfgets

Passing argument for fopen() in C issues


I'm working on a function that is supposed to read a file and I need the first line of the text file to be converted to an integer. The function takes the file in as a parameter, char *filename.

However, I'm getting an error when opening the file.

The error is the following: "passing argument of 2 of 'fopen' makes pointer from integer without a cast [-Wint-conversion] gcc"

 FILE *fp = fopen(filename, 'r'); //Line with error

 char str[6]; //since the first line is a 5 digit number
 fgets(str, 6, fp);
 sscanf(str, "%d", *number); //number is the pointer I'm supposed to save this value to, it is also a parameter for the function

I'm very new to C. So, I would appreciate any help. Thanks


Solution

  • If you will look through the description of the function fopen you will see that it is declared like

    FILE *fopen(const char * restrict filename, const char * restrict mode);
    

    That is the both parameters have the pointer type const char *.

    So instead of the integer character constant 'r' as the second argument you need to use string literal "r"

    FILE *fp = fopen(filename, "r");
    

    Also you have to write

    sscanf(str, "%d", &number);
    

    instead of

    sscanf(str, "%d", *number);
    

    if number has the type int. Or if it has the type int * then you need to write

    sscanf(str, "%d", number);
    

    And it is desirable to declare the character array as having at least 7 characters to allow to read also the new line character '\n' of the record

     char str[7]; //since the first line is a 5 digit number
     fgets(str, sizeof( str ), fp);
    

    Otherwise a next call of fgets can read an empty string.