Search code examples
cfilefopen

Trouble reading an integer with fscanf


I've been struggling for more than a day trying to figure out what's wrong with this piece of code,printf is always printing 0 on my screen.

#include <stdio.h>
#include <ctype.h>

int main()
{
int one=0,two=0;
FILE *arq;
arq = fopen ("testando.txt","w+");
fprintf(arq,"1,2,3\n");
fscanf(arq,"%d%d",&one,&two);
printf("%d %d\n",one,two);

return 0;

}


Solution

    1. Add commas in fscanf(arq,"%d%d",&one,&two);
    2. Reopen file with r flag - to read it
    3. Don't forget to close files ;)
    4. Opt. you can use return value of fscanf to check how much properties are filled

    This works fine:

    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
        int one=0,two=0;
        FILE *arq;
        arq = fopen ("testando.txt","w+");
        fprintf(arq,"1,2,3\n");
        fclose(arq);
    
        arq = fopen("testando.txt","r");
        int r = fscanf(arq,"%d,%d",&one,&two);
        fclose(arq);
        printf("%d %d %d\n",r, one,two);
    
        return 0;
    }
    

    Output:

    2 1 2