Advanced · C PROGRAMMING

File input and output

What you will learn

Write, rewind and read a temporary file.

Understand the concept

FILE represents a stream managed by the C library. tmpfile opens a temporary binary update stream, removed when closed. Check whether opening, writing and reading succeed. rewind moves the position to the beginning so that the program can read back its data. Some hosted compilers restrict filesystem access.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

Repair ready

Practise

Write two lines, rewind, and read them using a loop around fgets.

Common mistake

Always check the file pointer before using it. Reading a file changes its current position; it does not automatically start over.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    FILE *file = tmpfile();
    if (file == NULL) { perror("tmpfile"); return 1; }
    if (fputs("Repair ready\n", file) == EOF) { fclose(file); return 1; }
    rewind(file);
    char line[64];
    if (fgets(line, sizeof line, file) != NULL) printf("%s", line);
    else { fclose(file); return 1; }
    if (fclose(file) == EOF) return 1;
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
Repair ready
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA