The C fgets function reads characters until it encounters an End-Of-File (EOF), a newline character, or when n-1 characters are read.
This quick tutorial will discuss how to use the fgets function in C programs.
The general syntax for the C fgets function is as shown below:
The function accepts three parameters, namely:
- str – A Pointer to the array of characters where the reads string values are added.
- n – An integer value defining the maximum number of characters to be added to the str. The maximum number includes the null terminating character.
- stream – A pointer describing a file object to identify the input stream.
Fgets Return Values
On successful execution, the function will return str. If the function encounters an error, it returns a null pointer. Similarly, if the function terminates due to an EOF with no characters read, it returns a null pointer.
NOTE: Although a newline character will force the fgets function to stop, it is still included in the string copied as a valid character.
Fgets Function Example
Let us illustrate how to use the fgets function in C. Consider the example code shown below:
In the example above, the fgets function will open the fgets.txt file, read the first 100-1 (99) characters, and print them on the screen.
If we assume the contents of the fgets.txt file are:
Hello world!, this is fgets function in C.
Compiling and executing the above code should print out the lines above.
HINT: Unlike the gets function, the fgets function is safer since it checks the array bounds, preventing a buffer overflow.
This short guide discussed how to use the fgets function in C language to read characters from a stream until specific conditions are met.
Happy C time!