我已经编写了一个从文件中读取的代码,其中包含以下内容:
76 -1217454080 77 -1217458176 78 -1217462272
此代码:
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) ;
}
但是当到达循环(进入循环)时程序给我segmentation fault
,所以我尝试了这个代码(这是使第一个语句同时读取4个整数)并且它适用于读取4同时整数,但是当它进入循环时它又想要fscanf
,程序崩溃了!
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) ;
}
答案 0 :(得分:6)
fp = fscanf(fp , "%d" , &key);
你正在摧毁你的fp!
fscanf
返回int
,fp的类型为FILE*
。