0

Replace gets function with fgets in this code. Compile the program. Does the program comprise errors? If it does, explain the error and fix the code. Can anyone help me with it? Thank you.

#include <stdio.h>
int main(int argc, char **argv){
char buf[7]; // buffer for seven characters
gets(buf); // read from stdio (sensitive function!)
printf("%s\n", buf); // print out data stored in buf
return 0; // 0 as return value
}
Venkata Shivaram
  • 343
  • 4
  • 18
Geez567899
  • 13
  • 5

2 Answers2

1

Looking up some documentation for fgets,

Declaration

char *fgets(char *str, int n, FILE *stream)

Parameters

  • str − This is the pointer to an array of chars where the string read is stored.
  • n − This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.
  • stream − This is the pointer to a FILE object that identifies the stream where characters are read from.

So the difference is that we need to supply the stream (in this case, stdin aka input) and the length of the string to be read from stdin.

The following should work:

#include <stdio.h>

#define BUFLEN 7

int main(int argc, char **argv) {
  char buf[BUFLEN]; // buffer for seven characters
  fgets(buf, BUFLEN, stdin); // read from stdio
  printf("%s\n", buf); // print out data stored in buf
  return 0; // 0 as return value
}
0

The difference is that:

  • you pass the length of the buffer which avoids writing past end of buffer (what you want)
  • fgets leaves the '\n' in the buffer, so you have to manually remove it. More exactly the '\n' at the end of buffer says that the line could fit in the buffer - this is how to handle lines longer than the buffer.

Here is a possible code (no special processing for long lines):

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    char buf[7]; // buffer for seven characters
    if (NULL == fgets(buf, sizeof(buf), stdin)) { // read from stdio (sensitive function!)
        buf[0] = '\0';    // test end of file of read error and says empty data
    }
    else {
        size_t ix = strcspn(buf, "\n"); // remove an optional '\n'
        buf[ix] = '\0';
    }
    printf("%s\n", buf); // print out data stored in buf
    return 0; // 0 as return value
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252