c scanf不起作用。使用文件I / O.

时间:2016-06-24 07:22:01

标签: c file scanf

在Mac OS中使用C,我尝试提交I / O.

在我的代码中,如果是scanf 1,请尝试读取文件。

它在while循环中,如果是scanf 99,则结束。

如果我扫描1,请尝试正确读取文件。

但是在循环中,从不下一个scanf,所以它无限尝试文件读取。

我如何避免这种情况?

#include <stdio.h>

int freindFileReading();

int main(int argc, const char * argv[]) {


    while(1){
        int inputOfAct ;
        int Total_friendship_records;
        printf("Input what you want to act\n");
        printf("0  : Read data files\n");
        printf("99 : Quit\n");
        scanf("%d",&inputOfAct);
        switch(inputOfAct){
            case 1:
                printf("Reading..\n");
                Total_friendship_records = freindFileReading();
                printf("Total friendship records: %d\n",Total_friendship_records);
                break;
            case 99:
                return 0;
                break;
            default:
                printf("undefined input, retry\n");
        }
    }
    return 0;
}


int freindFileReading(){
    char * num1;
    char * num2;
    int there_is_num1=0;
    int Total_friendship_records = 0;

    FILE  *friendFile = freopen( "/Users/kimmyongjoon/Desktop/lwt/ltw1994/Project/Project/friend.txt", "r" ,stdin);

    if( friendFile != NULL )
    {
        char strTemp[255];
        char *pStr;

        while( !feof( friendFile ) )
        {
             if(strTemp[0]!='\n'){
                if(there_is_num1==0){
                    there_is_num1=1;
                    Total_friendship_records++;
                }else if(there_is_num1==1){
                    there_is_num1=0;
                }
            }
            pStr = fgets( strTemp, sizeof(strTemp), friendFile );
            printf( "%s", strTemp );
        }
        fclose( friendFile );
    }
    return Total_friendship_records;
}

1 个答案:

答案 0 :(得分:1)

问题出现在这个循环中 -

while( !feof( friendFile ) )
{
    if(strTemp[0]!='\n'){
        if(there_is_num1==0){
            there_is_num1=1;
            Total_friendship_records++;
        }else if(there_is_num1==1){
            there_is_num1=0;
        }
    }
    pStr = fgets( strTemp, sizeof(strTemp), friendFile );
    printf( "%s", strTemp );
}
应该避免

while(!feof())。在if条件下,您尝试这样做 -

if(strTemp[0]!='\n')

因为strTemp中没有任何内容存储在首位,所以这个条件不正确。

我建议你这个 -

while(fgets(strTemp,sizeof(strTemp),friendFile)!=NULL)  //read complete file
{
     if(there_is_num1==0){
        there_is_num1=1;
        Total_friendship_records++;
     }else if(there_is_num1==1){
        there_is_num1=0;
     }
     printf( "%s", strTemp );
}

循环将一直有效,直到fgets返回NULL。此外,在遇到换行符时,不需要检查'\n'作为fgets返回。