fgets() function in C

emily picture emily · Jan 4, 2010 · Viewed 37.5k times · Source

I know everybody has told me to use fgets and not gets because of buffer overflow. However, I am a bit confused about the third parameter in fgets(). As I understand it, fgets is dependent on:

char * fgets ( char * str, int num, FILE * stream );

char* str is the ptr to where my input will be stored.

num is the max number of character to be read.

but what is FILE *stream? If I am just prompting the user to enter a string (like a sentence) should I just type "stdin" ?

And should I type FILE *stdin at the top, near main()?

Answer

Carl Norum picture Carl Norum · Jan 4, 2010

You are correct. stream is a pointer to a FILE structure, like that returned from fopen. stdin, stdout, and stderr are already defined for your program, so you can use them directly instead of opening or declaring them on your own.

For example, you can read from the standard input with:

fgets(buffer, 10, stdin);

Or from a specific file with:

FILE *f = fopen("filename.txt", "r");
fgets(buffer, 10, f);