C Read Files
1. Opening a File for Reading
Use fopen() with read mode:
| Mode | Description |
|---|---|
"r" |
Read (file must exist) |
"r+" |
Read & write (file must exist) |
"a+" |
Read & append (creates file if not exist) |
2. Reading Functions in C
| Function | Description |
|---|---|
fgetc(fp) |
Reads a single character from the file |
fgets(buffer, size, fp) |
Reads a line/string from the file |
fscanf(fp, "format", &variables) |
Reads formatted input |
3. Example 1: Reading File Character by Character
-
fgetc()reads one character at a time. -
Loop continues until EOF (End of File) is reached.
4. Example 2: Reading File Line by Line Using fgets
-
fgets()reads up to size-1 characters or until newline. -
Includes the newline character at the end.
5. Example 3: Reading Formatted Data Using fscanf
Output (if data.txt has Age: 25 and Salary: 45000.50):
6. Checking File Open
-
Always check if the file exists before reading.
7. Key Points About Reading Files
-
Use read mode (
r) to open a file. -
Always check if
fopenwas successful. -
Functions for reading:
-
fgetc()→ single character -
fgets()→ line/string -
fscanf()→ formatted input
-
-
Loop until EOF for complete reading.
-
Always close files with
fclose()after reading.
