Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing gets() with fgets()

Tags:

c

fgets

gets

I've been testing this struct out and I get warning about using gets. Somebody mentioned to use fgets instead and replace the end with '\0'. Any recommendation how I can change my code to do that?

void regCars(Car reg[], int *pNrOfCars) {
    char again[WORDLENGTH] = "yes", model[WORDLENGTH], tmp[WORDLENGTH];
    int year, milage;

    while (strcmp(again, "yes") == 0) {
        printf("Enter model:");
        gets(model);
        printf("Enter Year:");
        gets(tmp);
        year = atoi(tmp);
        printf("Enter milage:");
        gets(tmp);
        milage = atoi(tmp);
        reg[*pNrOfCars] = createCar(model, year, milage); 
        (*pNrOfCars)++;
        printf("Continue? (yes/no)");
        gets(again);
    }
}
like image 607
xxFlashxx Avatar asked Oct 08 '16 08:10

xxFlashxx


1 Answers

It's a little bit tricker than it looks. There's not much point just replacing gets with fgets(), if you then process a truncated line on over-long input and handle it as valid. You've merely replaced undefined behaviour with wrong behaviour.

if( fgets(line, sizeof(line), fp) )
{
   if(!strchr(line, '\n'))
   {
      /* line is too long, what you do is up to you, but normally
         we will discard it */
      int ch;

      while( (ch = fgetc(fp)) != EOF)
        if(ch == '\n')
          break;

   }
   else
   {
       /* line is a normal line with a trailing '\n' (gets trims the '\n')           */
   }
}
like image 183
Malcolm McLean Avatar answered Sep 23 '22 12:09

Malcolm McLean