用c语言读取文件错误

时间:2014-05-23 08:39:58

标签: c file

我已经编写了一个从文件中读取的代码,其中包含以下内容: 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) ;
            }

1 个答案:

答案 0 :(得分:6)

fp = fscanf(fp , "%d" , &key);

你正在摧毁你的fp! fscanf返回int,fp的类型为FILE*