To read a file in C, you must first open it in read mode ("r"). If the file does not exist, fopen() will return NULL, so checking the file pointer is even more critical when reading than it is when writing.
Depending on how your data is structured, you have three main ways to read text from a file:
scanf() but gets input from the file.Using fgets() is the professional standard for reading text files because it prevents buffer overflows by letting you set a character limit.
When reading a file, C needs to know when to stop. The constant EOF (End Of File) is a special value returned by reading functions when they reach the end of the data stream.
If your file contains structured data, like a list of ages or prices, fscanf() is the best tool for the job.
| Function | Best For... | Stops At... |
|---|---|---|
fgetc() |
Low-level parsing. | Every single character. |
fgets() |
Reading sentences/paragraphs. | Newline (\n) or Buffer limit. |
fscanf() |
Specific data types (int, float). | Whitespace or Tab. |
fgets(), it actually includes the newline character (\n) from the file in your string if it finds one. You might need to manually remove it if you plan to compare that string with another using strcmp().