My program don"t execute fscanf

My program just end directly,the program don"t execute fscanf function,how do i fix this problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <stdio.h>

 
int main()

{

    FILE *fp;

    int  i,j,var;

    fp = fopen("data2.txt","w");     /* open file pointer */

  

for ( i = 0; i < 5; i++ )

    {

       for ( j = 0; j < 5; j++ )

       {

        fscanf(fp,"%d",&var);

        printf("%c",var);

       }

       printf("\n");

    }

    fclose(fp);

}
Last edited on
closed account (E0p9LyTq)
After you attempt to open their file you don't check if the file was actually opened. If it wasn't you are trying to read data from a NULL stream.

Why doesn't the program open the file? Likely the file isn't in the same location the program executes from,
Open the file for input (reading).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

int main()
{
    // "r" open the file for reading
    FILE* fp = fopen( "data2.txt", "r" ) ;

    if( fp != NULL ) // if the file was opened
    {
        // try to read 5 integers from the file
        for( int i = 0 ; i < 5 ; ++i )
        {
            int var ;

            if( fscanf( fp, "%d", &var) == 1 ) // if one value was read in (successful scanf)
                printf( "%d\n", var ) ; // print the value that was read

            else puts( "input failure (failed to read an int)\n" ) ;
        }
    }

    else puts( "failed to open input file" ) ;
}
Topic archived. No new replies allowed.