Reading from Files in C
Reading data from files allows your program to process input stored in files. C provides several functions for reading from files.
1. Functions to Read from Files
Function | Description |
---|---|
fscanf(FILE *fp, const char *format, ...) | Reads formatted input from a file. |
fgets(char *str, int n, FILE *fp) | Reads a string from a file. |
fgetc(FILE *fp) | Reads a character from a file. |
fread(void *ptr, size_t size, size_t nmemb, FILE *fp) | Reads data from a file into an array. |
2. Example: Reading Text from a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
char buffer[100];
fptr = fopen("output.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
while (fgets(buffer, 100, fptr) != NULL) {
printf("%s", buffer);
}
fclose(fptr);
return 0;
}
3. Example: Reading Binary Data from a File
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
int numbers[5];
fptr = fopen("data.bin", "rb");
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
fread(numbers, sizeof(int), 5, fptr);
fclose(fptr);
printf("Data read from file:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Best Practices
- Use
fgets()
to read strings and avoid buffer overflows. - Check for end-of-file using
feof()
or the return values of reading functions. - Handle possible read errors, such as corrupted files or incorrect formats.
Don'ts
- Don't ignore the possibility of partial reads; always check the number of items read.
- Don't assume the file contains the expected data; validate inputs.
- Don't forget to close the file after reading.
Key Takeaways
- Reading from files allows your program to utilize external data sources.
- Various functions are available for reading text and binary data.
- Proper error handling ensures robust file reading operations.