Lesson contents

C — Reading and writing a temporary file

In C, tmpfile opens a temporary stream for both writing and reading. After writing the numbers, use fseek to return to the start before you read them with fscanf.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
lesson.c
#include <stdio.h>

int main(void) {
    FILE *file = tmpfile();
    if (file == NULL) return 1;
    fputc('A', file);
    rewind(file);
    printf("%c\n", fgetc(file));
    fclose(file);
}
Output
A
Advertisements

Sum two lines from a temporary report

tmpfile opens a temporary update stream. fseek switches from writing to reading at the start. fscanf returns 1 after a successful conversion, 0 for malformed input, and EOF at the end or on a read error.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    FILE *report = tmpfile();
    if (report == NULL) return 1;
    if (fputs("4\n7\n", report) == EOF || fseek(report, 0, SEEK_SET) != 0) {
        fclose(report);
        return 1;
    }
    int total = 0, value;
    int read_result;
    while ((read_result = fscanf(report, "%d", &value)) == 1) total += value;
    int valid = read_result == EOF && !ferror(report);
    if (fclose(report) != 0 || !valid) return 1;
    printf("%d\n", total);
    return 0;
}
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

GNU C Language Manual

Related tags

  • C
  • files
  • streams
  • resource management