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()
?
fgets() function in C The function reads a text line or a string from the specified file or console. And then stores it to the respective string variable. Similar to the gets() function, fgets also terminates reading whenever it encounters a newline character.
The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first.
fgets is a function in the C programming language that reads a limited number of characters from a given file stream source into an array of characters. fgets stands for file get string. It is included in the C standard library header file stdio. h .
C library function - fgets() The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
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);
Yes, you should just use stdin
. That is a predefined FILE *
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 for fgets
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With