The fgets()
function in C reads up to n
characters from the stream (file stream or standard input stream) to a string str
. The fgets()
function keeps on reading characters until:
(n-1)
characters have been read from the stream.fgets
terminates at the newline character but appends it at the end of the string str
. The function also appends the terminating null character at the end of the passed string.
char* fgets(char* str, int n, FILE* stream);
char* str
: pointer to an initialized string in which characters are copied.int n
: number of characters to copy.FILE* stream
: pointer to the file stream, this can be replaced by stdin
when reading from standard input.str
is returned. If there was an error or the end of file character is encountered before any content could be read, a NULL
pointer is returned.fgets
is safe to use in comparison to gets
since it checks for character array str
bounds. gets
keeps on reading characters from the users, until a newline character is encountered.
#include <stdio.h>int main(){char str[20];fgets(str, 20, stdin); // read from stdinputs(str); // print read content out to stdout// open the fileFILE *f = fopen("file.txt" , "r");// if there was an errorif(f == NULL){perror("Error opening file"); // print errorreturn(-1);}// if there was no errorelse{fgets(str, 20, f); // read from fileputs(str); // print read content out to stdout}fclose(f); // close filereturn(0);}
Enter the input below