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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
Learning file handling
Sample output
Stored message: Learning file handling
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Stored message: Learning file handling
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Open a file in write mode, close it, reopen it in read mode and display the stored line.
- 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.
