김명준
김명준

Reputation: 363

c scanf did not work. with file I/O

With C in Mac OS, I try to file I/O.

In my code, if scanf 1, try to read file.

It is in while loop and if scanf 99, end.

If I scanf 1, once try file read correctly.

But in loop, never next scanf, so It is infinitly try to file read.

How I avoid this 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;
}

Upvotes: 0

Views: 96

Answers (1)

ameyCU
ameyCU

Reputation: 16607

Problem is in this loop -

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()) should be avoided. And in if condition you try to do this -

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

As nothing is stored in strTemp in first place so this condition is not correct .

I would suggest you this -

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

Loop will work until fgets returns NULL.Also there isn't need to check for '\n' as fgets return as it encounters new line character.

Upvotes: 1

Related Questions