C PROGRAMMING PROGRAM • FILE HANDLING

Write to and Read from a Text File

Learn how to write to and read from a text file using a clear C program.

IntermediateFILE pointerfputs()fgets()

PROBLEM UNDERSTANDING

Input and expected output

Sample input
Learning file handling
Sample output
Stored message: Learning file handling

COMPLETE C PROGRAM

Complete C implementation

write-and-read-text-file.c
Open in compiler
#include <stdio.h>

int main(void)
{
    char message[300], stored[300];

    printf("Enter a message: ");
    fgets(message, sizeof message, stdin);
    FILE *file = fopen("message.txt", "w");
    if (file == NULL) { perror("message.txt"); return 1; }
    fputs(message, file);
    fclose(file);

    file = fopen("message.txt", "r");
    if (file == NULL) { perror("message.txt"); return 1; }
    if (fgets(stored, sizeof stored, file) != NULL) printf("Stored message: %s", stored);
    fclose(file);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Stored message: Learning file handling
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Open a file in write mode, close it, reopen it in read mode and display the stored line.
  3. Display the computed result.

Open a file in write mode, close it, reopen it in read mode and display the stored line.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.