Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets() function in C

Tags:

c

stdin

fgets

libc

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()?

like image 205
emily Avatar asked Jan 04 '10 19:01

emily


People also ask

What is fgets function in C?

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.

What is the function of fgets?

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.

Where is fgets in C?

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 .

What is the syntax of fgets?

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.


2 Answers

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);
like image 68
Carl Norum Avatar answered Oct 26 '22 23:10

Carl Norum


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).

like image 40
Brian Campbell Avatar answered Oct 27 '22 01:10

Brian Campbell