Working with Files in C

Lesson 15 of 15 · C

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.

ModeMeaningIf the file does not existIf it exists
"r"readingerror (NULL)reads from the beginning
"w"writinga new one is createdthe old content is deleted
"a"appending to the enda new one is createdwrites 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
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
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?