CC

C: Files – code examples

Contents

Write a file and read it line by line

Files#fopen#fgets#fprintf#fileCompare in all languages
Use case: Save and load logs, configurations or text data.
#include <stdio.h>

int main(void) {
    FILE *f = fopen("notizen.txt", "w");
    if (!f) return 1;
    fprintf(f, "Line 1\nLine 2\n");
    fclose(f);

    char zeile[100];
    f = fopen("notizen.txt", "r");
    if (!f) return 1;
    while (fgets(zeile, sizeof zeile, f)) printf("%s", zeile);
    fclose(f);
    return 0;
}

fopen/fclose open and close; fgets reads at most sizeof zeile characters and is therefore safe from buffer overflows. Every fopen needs an fclose.

Counting lines and words of a file

Files#fgetc#eof#file#argv
Use case: Simple text analysis: estimate the size of logs or text files (like the wc program).
#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    if (argc < 2) { fprintf(stderr, "Usage: %s file\n", argv[0]); return 1; }
    FILE *f = fopen(argv[1], "r");
    if (f == NULL) { perror(argv[1]); return 1; }
    int c, zeilen = 0, woerter = 0, im_wort = 0;
    while ((c = fgetc(f)) != EOF) {
        if (c == '\n') zeilen++;
        if (isspace(c)) im_wort = 0;
        else if (!im_wort) { im_wort = 1; woerter++; }
    }
    fclose(f);
    printf("%d lines, %d words\n", zeilen, woerter);
    return 0;
}

fgetc returns an int so that EOF (-1) stays distinguishable from the character 255 – that is why you must not use char c. Call it as: ./zaehle notizen.txt.

Binary data with fwrite / fread

Files#fwrite#fread#binary#file
Use case: Store number series or structs compactly and load them again (save games, caches).
#include <stdio.h>

int main(void) {
    int daten[] = {10, 20, 30, 40};
    FILE *f = fopen("daten.bin", "wb");
    if (f == NULL) return 1;
    fwrite(daten, sizeof daten[0], 4, f);
    fclose(f);

    int gelesen[4];
    f = fopen("daten.bin", "rb");
    if (f == NULL) return 1;
    size_t n = fread(gelesen, sizeof gelesen[0], 4, f);
    fclose(f);
    printf("%zu read, last value %d\n", n, gelesen[n - 1]);
    return 0;
}

fwrite/fread copy bytes 1:1 – do not forget the mode "wb"/"rb". The return value is the number of elements. The format is platform-dependent (byte order, sizes).