2016-06-24 4 views
0

Mac OSではCを使用して、I/Oをファイルにしようとします。c scanfが機能しませんでした。ファイルI/Oを使って

私のコードでは、scanf 1の場合、ファイルを読み込もうとします。

whileループ内にあり、scanf 99の場合は終了します。

私がscanf1の場合、一度正しくファイルを読み込んでみてください。

しかし、ループでは、決して次の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

問題は、このループである -

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); 
} 

ループは、それが改行文字に遭遇すると'\n'fgetsとしてリターンをチェックする必要がありませんfgets戻りNULL .Alsoまで動作します。

関連する問題