2016-06-24 13 views
0

Mit C in Mac OS, ich versuche, I/O-Datei.c scanf hat nicht funktioniert. mit Datei-I/O

In meinem Code, wenn scanf 1, versuchen Sie, Datei zu lesen.

Es ist in While-Schleife und wenn scanf 99, Ende.

Wenn ich scanf 1, einmal versuchen, Datei richtig gelesen.

Aber in der Schleife, nie nächste scanf, so ist es unendlich versuchen, Datei lesen.

Wie vermeide ich diese Situation?

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

Antwort

1

Problem ist in dieser Schleife -

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()) sollte vermieden werden. Und in if Zustand versuchen Sie, dies zu tun -

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

Da nichts in strTemp an erster Stelle gespeichert ist, so dass diese Bedingung nicht korrekt ist.

Ich würde Sie dies vorschlagen -

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

Schleife arbeiten, bis fgets kehrt NULL .also ist es nicht für '\n' als fgets Rückkehr müssen prüfen, wie es Zeilenendmarke trifft.