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()
?
Broadly there are two ways you can communicate with files in C. One is using the low-level OS dependent system calls such as
open()
,read()
,write()
etc which work with file descriptors. Another one is usingFILE
structures which are used in C library functions likefread()
,fwrite()
etc including the one you mentioned above.As it is with the UNIX philosophy, everything is a file. So even the standard input (
stdin
) is treated as a pointer to aFILE
structure.tl;dr Yes, you should use
stdin
forFILE* stream
in your call tofgets()
Yes, you should just use
stdin
. That is a predefinedFILE *
that reads from the standard input of your program. And it should already be defined if you have a#include <stdio.h>
at the top of your file (which you'll need forfgets
).FILE is the standard C file. Yes, if you want to read from standard input, stdin is the correct symbol.
You are correct.
stream
is a pointer to aFILE
structure, like that returned fromfopen
.stdin
,stdout
, andstderr
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:
Or from a specific file with: