The C library fgets(FILE *stream) function gets the next character ( unsigned char) from the specified stream and advances the position indicator for the stream.It is commonly used for reading input from a file or from standard input (stdin).
SyntaxFollowing is the C library syntax of the fgets() function −
char *fgets(char *str, int n, FILE *stream);Parameters
This function accepts the three parameters −
On success, fgets returns the same pointer str that was passed in, which now contains the string that was read. If an error occurs, or if end-of-file is reached and no characters were read, fgets returns NULL.
Example 1: Reading a Line from Standard InputThis example reads a line of text from standard input and prints it. The buffer size is 50, allowing for lines up to 49 characters long (plus the null terminator).
Below is the illustration of C library fgets() function.
#include <stdio.h> int main() { char buffer[50]; printf("Enter a string: "); if (fgets(buffer, sizeof(buffer), stdin) != NULL) { printf("You entered: %s", buffer); } else { printf("Error reading input."); } return 0; }Output
The above code produces following result−
Enter a string: Welcome to tutorials point You entered: Welcome to tutorials pointExample 2: Handling End-of-File
This example reads a file line by line with a smaller buffer size, handling the end-of-file condition explicitly. If the end of the file is reached, a message is printed.
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); char buffer[20]; if (file == NULL) { printf("Failed to open file.\n"); return 1; } while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("Read: %s", buffer); } if (feof(file)) { printf("End of file reached.\n"); } else if (ferror(file)) { printf("An error occurred.\n"); } fclose(file); return 0; }Output
After execution of above code, we get the following result
(This output will depend on the contents of example.txt) End of file reached.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4