Andrew
Andrew

Reputation: 1025

reading input with fgets(goes into endless loop)

I have this application where it reads user input with fgets. It works fine and have no problem if I take user input while program is running. But if I feed a file say "./myprog < in.txt", it goes into infinite loop and print my custom error message that I show when user doesn't provide valid input all over the screen. It's like return key is pressed. How do I solve that problem?

This is one section of my program that's has fgets

while(1){
  mainMenu(&choice);
  switch(choice)
  {
     case 0: 
        return 0;

     case 1: //Add movies 
        getMovieData(&list);
        break;

     case 2:
        ....some initialization... 
        printf("Provide a name to delete : ");
        fgets(inputBuffer,sizeof(inputBuffer),stdin);
    trimWhiteSpace(inputBuffer);
        deleteMovie(&list,inputBuffer);
        break;

     case 3: //List all movies
        printMovieData(list);
        break;

     case 4: //List movies by genre
        inputBuffer[0] = '\0';
        printf(".....");
    fgets(inputBuffer,sizeof(inputBuffer),stdin);               
        trimWhiteSpace(inputBuffer);
        if(!isNum(inputBuffer,&genreChoice)){ 
           showMessage("Number Expected\n");
           break;
        }
        else if(!checkNumberValidity(&genreChoice,1,6)){
           showMessage("Choose from 1 to 7\n");
           break;
        }
        else printMoviesByGenre(list,getGenre(genreChoice-1));
        break;

  }

}

while(1){
  printf("Provide the number of movies you would like to enter: ");
  fgets(temp, sizeof(temp), stdin);
  trimWhiteSpace(temp);         
  if(!isNum(temp,&numMovie)) printf("Enter a numeric value\n");
  else if(!checkNumberValidity(&numMovie,1,MAX_MOVIES)) printf("No greater than %d\n",MAX_MOVIES);  
  else break;

}

Upvotes: 0

Views: 5537

Answers (2)

Jarhmander
Jarhmander

Reputation: 344

Check the return value of fgets. It returns NULL on failure. At the end of the stream, fgets return NULL and feof(file) will be != 0, indicating you reached the end of stream (EOF, end of file).

As Charlie Burns said, you must exit on end of input, so do something like this:

if (fgets(temp, sizeof(temp), stdin) == NULL)
    exit(EXIT_SUCCESS);

... in your while(1) loop.

Related: fgets and dealing with CTRL+D input

Upvotes: 1

Gabson
Gabson

Reputation: 431

i don't think the infinite loop comes from fgets. But its not well declared fgets(inputBuffer,sizeof(inputBuffer),stdin); second argument must be a size, size that says how much char you wanna read. Show us where is you printf that you see during the infinite loop.

Upvotes: 0

Related Questions