๐ 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 :
