Written: August 15, 2026
File output starts with fopen in write mode, a successful FILE, then fputs/fprintf, then fclose.
This walkthrough keeps the logic small and readable so you can type it, run it, and then change one input at a time to see what happens.
What you will build
You will prompt for a string, open output.txt for writing, store the string, and close the file.
- Read a line into a buffer
- fopen(“output.txt”, “w”)
- Check for NULL
- fputs the string and fclose
Working C example
include <stdio.h>
int main(void) {
char s[256];
FILE fp;
printf("Enter text: ");
if (!fgets(s, sizeof s, stdin)) return 1;
fp = fopen("output.txt", "w");
if (!fp) {
printf("Could not open file\n");
return 1;
}
fputs(s, fp);
fclose(fp);
printf("Wrote output.txt\n");
return 0;
}
How the logic works
Read the program top to bottom: includes and main first, then the statements that change variables, then the print that proves the result.
If your output looks wrong, print the variables before and after the critical lines. That single habit catches most beginner bugs faster than rewriting the whole file.
Always check fopen. On failure, printing a clear error beats silently continuing with a NULL pointer.
Keep learning
If this walkthrough on C Program to Write a String into a File helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.
Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.