File reading is a crucial skill in C programming. It allows you to access and process data stored in external files, enabling your programs to work with persistent information.
Before reading a file, you need to open it using the fopen()
function from the stdio.h library. This function returns a file pointer that you'll use for subsequent operations.
FILE *file_pointer;
file_pointer = fopen("example.txt", "r");
if (file_pointer == NULL) {
printf("Error opening file!\n");
exit(1);
}
The "r" mode opens the file for reading. Always check if the file was opened successfully before proceeding.
C provides several functions for reading file contents. The choice depends on your specific needs:
Use fgetc()
to read a single character at a time:
int ch;
while ((ch = fgetc(file_pointer)) != EOF) {
putchar(ch);
}
For line-by-line reading, fgets()
is your go-to function:
char buffer[100];
while (fgets(buffer, sizeof(buffer), file_pointer) != NULL) {
printf("%s", buffer);
}
When dealing with structured data, fscanf()
allows you to read formatted input:
int num;
char str[50];
while (fscanf(file_pointer, "%d %s", &num, str) == 2) {
printf("Number: %d, String: %s\n", num, str);
}
Always close the file when you're done to free up system resources:
fclose(file_pointer);
Be aware of these common issues when reading files in C:
By mastering file reading in C, you'll be able to create more versatile and data-driven programs. Practice with different file types and sizes to hone your skills.
To further enhance your understanding of file operations in C, explore these related topics: