Reading from Files
1. Introduction
Reading from files in C means retrieving data stored in a file and using it in a program. Files are used to store data permanently. When a program needs old or saved data, it must read the data from a file.
Reading from files is commonly used in:
-
Student record systems
-
Report generation
-
Banking and accounting software
-
Database-based applications
C provides many file handling functions to read data from files efficiently.
2. Steps to Read from a File in C
To read data from a file, the following steps are followed:
-
Declare a file pointer
-
Open the file in read mode (
"r") -
Read data using file reading functions
-
Close the file
3. File Pointer for Reading
A file pointer is required to access a file.
Declaration
-
FILEis a structure defined instdio.h -
fpstores the address of the file
4. Opening a File in Read Mode
To read a file, it must be opened using the fopen() function.
Syntax
Example
âš Important Points:
-
If the file does not exist,
fopen()returns NULL -
Always check whether the file opened successfully
Example with Checking
5. Reading Data Using fgetc()
Description
-
Reads one character at a time
-
Returns the character read
-
Returns EOF at end of file
Syntax
Example Program
Use
-
Useful for reading character-by-character
-
Best for text files
6. Reading Data Using fgets()
Description
-
Reads one line at a time
-
Stops at newline or end of file
Syntax
Example Program
Advantages
-
Safe for reading strings
-
Prevents buffer overflow
7. Reading Data Using fscanf()
Description
-
Reads formatted data
-
Works like
scanf(), but reads from a file
Syntax
Example Program
Limitation
-
Stops reading at spaces
-
Not suitable for full lines
8. End of File (EOF)
Definition
EOF (End of File) is a special constant used to detect when the file has no more data.
Example
9. Reading Binary Files
Binary files store data in binary format and are faster than text files.
Function Used: fread()
Syntax
Example: Reading a Structure from a Binary File
10. Comparison of File Reading Functions
| Function | Reads | Best Use |
|---|---|---|
fgetc() |
Character | Character-wise reading |
fgets() |
Line | Line-wise reading |
fscanf() |
Formatted data | Structured data |
fread() |
Binary data | Binary files |
11. Common Errors While Reading Files
-
File not opened properly
-
Reading beyond end of file
-
Using wrong file mode
-
Forgetting to close the file
12. Advantages of Reading from Files
-
Access to permanent data
-
Useful for large data handling
-
Reduces memory usage
-
Makes programs more efficient
13. Conclusion
Reading from files in C allows programs to retrieve stored data efficiently. By using different file reading functions like fgetc(), fgets(), fscanf(), and fread(), programmers can read data in various formats. Proper use of file reading techniques helps in building reliable and practical applications.