So far the data came from the keyboard, and the results went to the screen. Files make it possible for a program to read data from a file and to save the result – even after the program ends. At some competitions the input is read from a file, so this lesson is also a preparation for that.
Before you start: prior knowledge you need – strings, structures, loops. How to learn: retype and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are in C (C11); they have been checked to compile (gcc -Wall) and give the output shown.
Opening and closing: fopen and fclose
Working with a file has three steps: open (fopen), read or write, close (fclose). fopen returns a pointer of type FILE *, or NULL if opening failed – this is always checked.
Mode
Meaning
If the file does not exist
If it exists
"r"
reading
error (NULL)
reads from the beginning
"w"
writing
a new one is created
the old content is deleted
"a"
appending to the end
a new one is created
writes after the existing content
#include <stdio.h>
int main(void) {
FILE *f = fopen("hello.txt", "w"); /* open for writing */
if (f == NULL) {
printf("Cannot open the file.\n");
return 1;
}
fprintf(f, "Hello from the file!\n"); /* like printf, but into the file */
for (int i = 1; i <= 3; i++)
fprintf(f, "Line %d\n", i);
fclose(f); /* always close it */
printf("Written to hello.txt\n");
return 0;
}
The file hello.txt is created in the folder the program is run from (in Code::Blocks that is the project folder). Open it in Notepad and check its content.
Reading numbers: fscanf
fscanf(f, ...) works like scanf, but reads from a file. It returns the number of values read successfully, and at the end of the file it returns EOF. That is why an unknown number of values is read with the loop while (fscanf(...) == 1).
The file numbers.txt contains numbers separated by spaces or new lines, e.g. 4 8 15 16 23 42:
#include <stdio.h>
int main(void) {
FILE *f = fopen("numbers.txt", "r");
if (f == NULL) {
printf("There is no file numbers.txt\n");
return 1;
}
int x, n = 0, sum = 0, max = 0;
while (fscanf(f, "%d", &x) == 1) { /* read while there are numbers */
if (n == 0 || x > max) max = x;
sum += x;
n++;
}
fclose(f);
if (n > 0)
printf("Numbers: %d, sum: %d, average: %.2f, largest: %d\n", n, sum, (double)sum / n, max);
return 0;
}
For the numbers above the program prints:
Numbers: 6, sum: 108, average: 18.00, largest: 42
Reading line by line: fgets
fgets(text, size, f) reads one whole line (with spaces) and returns NULL at the end of the file. The character '\n' stays at the end of the line that was read, and it is usually removed.
#include <stdio.h>
#include <string.h>
int main(void) {
/* first we create a file with a few lines */
FILE *f = fopen("poem.txt", "w");
if (f == NULL) return 1;
fprintf(f, "Programming is fun\nC is a fast language\n\nThe end\n");
fclose(f);
/* then we read it line by line */
f = fopen("poem.txt", "r");
if (f == NULL) return 1;
char line[200];
int count = 0;
while (fgets(line, sizeof line, f) != NULL) {
line[strcspn(line, "\n")] = '\0'; /* remove '\n' from the end */
count++;
printf("%d: %s (%d characters)\n", count, line, (int)strlen(line));
}
fclose(f);
return 0;
}
The program prints:
1: Programming is fun (18 characters)
2: C is a fast language (20 characters)
3: (0 characters)
4: The end (7 characters)
Input from one file, output to another
A typical task: read data from input.txt, process it and write the result to output.txt. Two files can be open at the same time.
The first line of input.txt holds the number of students n, followed by a name and points for each of them. The ones with at least 50 points should be written to output.txt:
#include <stdio.h>
int main(void) {
FILE *in = fopen("input.txt", "r");
FILE *out = fopen("output.txt", "w");
if (in == NULL || out == NULL) {
printf("Error opening the files.\n");
return 1;
}
int n, points, passed = 0;
char name[30];
fscanf(in, "%d", &n);
for (int i = 0; i < n; i++) {
fscanf(in, "%29s %d", name, &points);
if (points >= 50) {
fprintf(out, "%s %d\n", name, points);
passed++;
}
}
fprintf(out, "Passed: %d of %d\n", passed, n);
fclose(in);
fclose(out);
return 0;
}
input.txt
4
Marko 45
Ana 92
Iva 50
Luka 30
output.txt after running
Ana 92
Iva 50
Passed: 2 of 4
Nothing is printed on the screen – the whole result is in the file.
Appending to the end: mode "a"
#include <stdio.h>
/* every call adds one line to the end of the log */
void logMessage(const char *message) {
FILE *f = fopen("log.txt", "a");
if (f == NULL) return;
fprintf(f, "%s\n", message);
fclose(f);
}
int main(void) {
remove("log.txt"); /* start from an empty file */
logMessage("Program started");
logMessage("Data loaded");
logMessage("Finished");
/* read the whole log character by character */
FILE *f = fopen("log.txt", "r");
if (f == NULL) return 1;
int c;
while ((c = fgetc(f)) != EOF)
putchar(c);
fclose(f);
return 0;
}
The program prints:
Program started
Data loaded
Finished
If the function logMessage used the mode "w", only the last line would stay in the log – every opening would delete the previous content. fgetc reads one character; the variable c is of type int so that it can also hold the value EOF.
Competitions: freopen
If a task requires reading from a file, and the program has already been written with scanf/printf, it is enough to redirect the standard input and output at the beginning of main:
#include <stdio.h>
int main(void) {
/* from this moment scanf reads from input.txt, and printf writes to output.txt */
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n", a + b);
return 0;
}
Before submitting, check the exact file names in the task statement. When you practise at home, you can comment out these two lines and type the data on the keyboard.
Practice tasks
Every task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: easy
The longest line
The file input.txt contains text in several lines (every line has at most 200 characters). Write to the file output.txt the number and the content of the longest line (if there are several, the first of them), in the form number: text.
In the example, the content of input.txt is on the left, and the content of output.txt on the right.
Example
Input
A short line
This is the longest line here
A medium line
Output
2: This is the longest line here
Hint
Read with fgets, remove '\n', remember the greatest length and copy that line with strcpy.
Solution (C)
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *in = fopen("input.txt", "r");
FILE *out = fopen("output.txt", "w");
if (in == NULL || out == NULL) return 1;
char line[205], longest[205] = "";
int count = 0, longestNo = 0, longestLen = -1;
while (fgets(line, sizeof line, in) != NULL) {
line[strcspn(line, "\n")] = '\0';
count++;
int len = (int)strlen(line);
if (len > longestLen) { /* strictly greater: the first longest one stays */
longestLen = len;
longestNo = count;
strcpy(longest, line);
}
}
if (longestNo > 0)
fprintf(out, "%d: %s\n", longestNo, longest);
fclose(in);
fclose(out);
return 0;
}
TASK 02Difficulty: medium
Grade statistics
The file input.txt contains grades (integers from 1 to 5) separated by spaces and new lines; their number is not known in advance. Write to output.txt how many of each grade there were (from 5 down to 1, in the form grade: count) and the average to two decimal places.
Example
Input
5 4 5 3
2 5 4
5 4
Output
5: 4
4: 3
3: 1
2: 1
1: 0
Average: 4.11
Hint
An array of counters int count[6] = {0}; every grade x that is read increases count[x]. Read with while (fscanf(in, "%d", &x) == 1).
Solution (C)
#include <stdio.h>
int main(void) {
FILE *in = fopen("input.txt", "r");
FILE *out = fopen("output.txt", "w");
if (in == NULL || out == NULL) return 1;
int count[6] = {0}, x, n = 0, sum = 0;
while (fscanf(in, "%d", &x) == 1) {
if (x >= 1 && x <= 5) {
count[x]++;
sum += x;
n++;
}
}
for (int g = 5; g >= 1; g--)
fprintf(out, "%d: %d\n", g, count[g]);
if (n > 0)
fprintf(out, "Average: %.2f\n", (double)sum / n);
fclose(in);
fclose(out);
return 0;
}
Common mistakes and tips
Always check whether fopen returned NULL – the most common reason is a wrong file name or a wrong folder.
The mode "w" deletes the existing content of a file as soon as it is opened; to append, use "a".
Do not forget fclose: until the file is closed, part of the written text may stay in memory and not reach the disk.
The loop while (!feof(f)) is a common mistake – the last value is processed twice. Check the return value of fscanf/fgets.
In a Windows path the backslash is written twice: "C:\\data\\input.txt", or the ordinary / is used.
Check your knowledge
Open the quiz
Files
1. What does fopen return if a file opened for reading does not exist?
2. What does the mode "w" do with an existing file?
3. When does the loop while (fscanf(f, "%d", &x) == 1) end?
4. Which function reads a whole line of text with spaces?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.