Reputation: 151
I have write a code for read from file , which has the following contant :
76 -1217454080 77 -1217458176 78 -1217462272
by this code :
FILE* fp;
if((fp = fopen("test" , "r")) < 0 )
printf("ERROR in FILE \n") ;
int old_fp = fp ;
int shm , key ;
fp = fscanf(fp , " %d%d" , &key , &shm) ;
if(fp < 0)
printf("ERROR in fscanf \n ");
printf("%d , %d \n " , key , shm) ;
while( fp != EOF)
{
if(key == 5)
break ;
fp = fscanf(fp , "%d" , &key) ;
fp = fscanf(fp , "%d" , &shm) ;
printf("%d , %d\n" , key , shm) ;
}
but when reach the loop (enter the loop) the program give me segmentation fault
, so i have tried ny this code (which is make first statement read 4 integers at the same time ) and it works for reading 4 integers at same time , but it again when it enter the loop , and it want to do fscanf
, the program crash !
FILE* fp;
if((fp = fopen("test" , "r")) < 0 )
printf("ERROR in FILE \n") ;
int old_fp = fp ;
int shm , key ;
int ss , kk ;
fp = fscanf(fp , "%d%d%d%d" , &key , &shm,&ss,&kk) ;
printf("the result is %d %d " , ss , kk );
if(fp < 0)
printf("ERROR in fscanf \n ");
printf("%d , %d \n " , key , shm) ;
while( fp != EOF)
{
if(key == 5 )
break ;
// it's crash here
fp = fscanf(fp , "%d" , &key) ;
fp = fscanf(fp , "%d" , &shm) ;
printf("%d , %d \n " , key , shm) ;
}
Upvotes: 0
Views: 176
Reputation: 2232
fp = fscanf(fp , "%d" , &key);
You are destroying your fp!
fscanf
returns an int
and fp is of type FILE*
.
Upvotes: 6