Friday, September 9, 2011

DIFFERENCE BETWEEN fgets() and gets()


Two main differences:

1. fgets() allows you to specify the maximum number of characters to
read from the stream;

     gets() does not. If the input stream contains more characters than the target buffer is sized to hold, gets() will happily write those extra characters to the memory beyond the end of the buffer, potentially clobbering something important. Numerous
worms and viruses exploit such buffer overruns to propagate themselves. Because of this, use of gets() is *very strongly* discouraged.

2. If input is terminated by a newline character

  fgets() will store the trailing newline in the target buffer if there is enough room.
 
 gets() will not store the trailing newline in the buffer.

Prototypes:

#include <stdio.h>
 
char *fgets(char *s, int size, FILE *stream);
char *gets(char *s);

These are functions that will retrieve a newline-terminated string from the console or a file. In other normal words, it reads a line of text. The behavior is slightly different, and, as such, so is the usage.
One difference here between the two functions: gets() will devour and throw away the newline at the end of the line, while fgets() will store it at the end of your string (space permitting).
Here's an example of using fgets() from the console, making it behave more like gets():
char s[100];
gets(s);  // read a line (from stdin)
fgets(s, sizeof(s), stdin); // read a line from stdin
 
In this case, the sizeof() operator gives us the total size of the array in bytes, and since a char is a byte, it conveniently gives us the total size of the array.

Return Value

Both gets() and fgets() return a pointer to the string passed.
On error or end-of-file, the functions return NULL.

char s[100];
 
gets(s); // read from standard input (don't use this--use fgets()!)
 
fgets(s, sizeof(s), stdin); // read 100 bytes from standard input
 
fp = fopen("datafile.dat", "r"); // (you should error-check this)
fgets(s, 100, fp); // read 100 bytes from the file datafile.dat
fclose(fp);
 
fgets(s, 20, stdin); // read a maximum of 20 bytes from stdin

No comments:

Post a Comment