Index
- [[#fgets-function|
fgets
Function]] - [[#fgets-limitation-null-termination|
fgets
Limitation Null termination]]
fgets
Function
You can use fgets()
function is used to read a line of text from a file or input from the user.
It is declared in the stdio.h
header file as follows:
The function takes three arguments:
str
: a pointer to the buffer where the line of text is storedn
: the maximum number of characters to readstream
: a pointer to the input stream to read from
The fgets
function reads characters from the input stream until:
- it encounters a newline character (
'\n'
) - it encounters the end-of-file indicator (
EOF
) - it has reached the maximum numbers of characters that can be stored in the variable (
sizeof(fullName) - 1
).- in the example above: (30 -1)
User Input Example:
File Input Example:
This program opens a file named “example.txt” for reading, then reads lines from the file using fgets
and prints them to the console using printf
. Note that fgets
reads at most 100-1
characters at a time to avoid buffer overflow.
fgets
Limitation: Null termination
fgets
appends a null character ('\0'
) to the end of the string it reads, so:
- the buffer passed to
fgets
must be large enough to accommodate the null character.