C Read from Files โ Read Text and Binary Data Easily
Introduction โ How to Read Files in C?
In C programming, reading files allows your program to load external data such as configuration files, logs, or binary datasets. C provides functions like fscanf(), fgets(), and fread() to support both text-based and binary file input operations.
In this guide, youโll learn:
- How to open files for reading
- Use
fscanf(),fgets(), andfread()effectively - Handle common input errors and check for end-of-file
- Differences between text and binary file reading
Opening Files for Reading
Before reading from a file, you must open it in read mode using fopen():
FILE *fp = fopen("data.txt", "r"); // For text
FILE *fp = fopen("data.bin", "rb"); // For binary
Always check if the file opened successfully:
if (fp == NULL) {
perror("Failed to open file");
return 1;
}
Reading from Text Files
fscanf() โ Read Formatted Input
char name[50];
int age;
fscanf(fp, "%s %d", name, &age);
- Similar to
scanf()but reads from file - Good for structured text (like CSV, logs)
fgets() โ Read Line-by-Line
char line[100];
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}
- Reads a line of text (including spaces)
- Stops at newline or EOF
fgetc() โ Read One Character at a Time
int ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
- Good for character-by-character processing
Reading from Binary Files
fread() โ Read Raw Data Blocks
int nums[3];
fread(nums, sizeof(int), 3, fp);
Syntax:
fread(pointer, size_of_each_item, number_of_items, file_pointer);
- Reads data directly into memory
- Used for fast or structured binary data reading
Detecting End-of-File & Errors
feof() โ End of File Detection
while (!feof(fp)) {
// Safe read loop
}
ferror() โ Check for I/O Errors
if (ferror(fp)) {
printf("An error occurred while reading the file.\n");
}
Use Cases
| Task | Function |
|---|---|
| Reading settings | fscanf(), fgets() |
| Parsing line-by-line logs | fgets() |
| Reading binary blobs | fread() |
| File scanning | fgetc() |
Best Practices & Tips
Best Practice:
Always check if the file pointer (FILE *) is NULL before attempting any operation.
Tip:
Use fgets() instead of fscanf() when reading unpredictable or multiline textโit’s safer and handles spaces.
Pitfall:
Do not use feof() as the sole loop conditionโcombine it with read result checks.
Summary โ Recap & Next Steps
C provides a flexible and efficient set of tools for reading both text and binary files. Whether reading lines, words, or raw bytes, file input is essential for dynamic applications and data-driven programs.
Key Takeaways:
- Use
"r"or"rb"mode withfopen()to read files - Use
fscanf()for formatted text,fgets()for lines,fread()for binary - Always validate file and I/O operation success
- Use
feof()andferror()for robust error handling
Real-World Relevance:
Used in data importers, game save loaders, log parsers, configuration loaders, and binary file readers.
Frequently Asked Questions (FAQ)
How do I read a file line by line in C?
Use fgets(buffer, size, file_pointer); in a loop.
Can I read both text and binary files?
Yes. Use "r" or "rb" mode accordingly and choose between fscanf()/fgets() or fread().
What is the difference between fscanf() and fgets()?
fscanf() reads formatted input and skips whitespace; fgets() reads full lines including spaces.
What happens if I read past the end of a file?
It causes feof() to return true. Use feof() and check return values to prevent errors.
Do I need to close the file after reading?
Yes. Always call fclose(fp); to release file resources.
Share Now :
