C Read Files
Reading files means loading data from a file on disk into your C program. In C, you open a file in read mode, read data through a FILE * pointer, and close the file when you are done.
File reading is useful when a program needs to load saved text, settings, scores, logs, or other data that was created earlier.
Open A File For Reading
Use fopen with mode "r" to open an existing file for reading. If the file cannot be opened, fopen returns NULL, so always check before reading.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("animals.txt", "w");
if (file == NULL) {
printf("Could not create file.\n");
return 1;
}
fprintf(file, "cat\n");
fprintf(file, "dog\n");
fprintf(file, "bird\n");
fclose(file);
file = fopen("animals.txt", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
char line[50];
printf("File contents:\n");
while (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}
Output:
File contents:
cat
dog
bird
This example creates a small file first so the program can be run by itself. In a real program, the file might already exist before the program starts.
Read Lines With fgets
The fgets function reads one line, or part of a line, into a character array. It needs three arguments: the array, the size of the array, and the file pointer.
The condition fgets(line, sizeof(line), file) != NULL keeps reading until there are no more lines. If the line in the file contains a newline character, fgets keeps it in the array, which is why the example prints with printf("%s", line) instead of adding another \n.
Read One Character At A Time
Use fgetc when you need to process a file character by character. It returns one character as an int, or EOF when the end of the file is reached.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("note.txt", "w");
if (file == NULL) {
printf("Could not create file.\n");
return 1;
}
fputs("C files\n", file);
fclose(file);
file = fopen("note.txt", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
int ch;
int count = 0;
while ((ch = fgetc(file)) != EOF) {
count++;
}
fclose(file);
printf("Characters read: %d\n", count);
return 0;
}
Output:
Characters read: 8
The variable ch is an int, not a char, because it must be able to store every possible character value and the special value EOF.
Read Formatted Data With fscanf
The fscanf function works like scanf, but it reads from a file. It is useful when the file has predictable formatted data, such as a name followed by a number.
#include <stdio.h>
int main(void)
{
FILE *file = fopen("scores.txt", "w");
if (file == NULL) {
printf("Could not create file.\n");
return 1;
}
fprintf(file, "Ada 95\n");
fprintf(file, "Ben 88\n");
fclose(file);
file = fopen("scores.txt", "r");
if (file == NULL) {
printf("Could not open file.\n");
return 1;
}
char name[20];
int score;
while (fscanf(file, "%19s %d", name, &score) == 2) {
printf("%s scored %d\n", name, score);
}
fclose(file);
return 0;
}
Output:
Ada scored 95
Ben scored 88
The width %19s leaves room for the string’s null terminator in name[20]. This is safer than using plain %s because it limits how many characters can be stored.
Common Reading Functions
| Function | Use |
|---|---|
fgets |
Read a line of text into a string. |
fgetc |
Read one character at a time. |
fscanf |
Read formatted values from predictable text. |
Important Rules
- Include
<stdio.h>before using file functions. - Use mode
"r"to read an existing file. - Check whether
fopenreturnedNULL. - Use a large enough character array when reading text.
- Check the return value of
fgetsorfscanfto know whether reading worked. - Call
fclosewhen you are finished with the file.
The key idea is that reading files in C follows a simple pattern: open the file, check for errors, read the data, and close the file.
