Nearby lessons

70 of 72

C - Writing to a File

Writing to a file allows a C program to save information for later use. Learn how to write formatted data with fprintf() and text with fputs().

1. Write Data Using fprintf()

fprintf() works like printf(), but sends the formatted output to a file instead of the screen.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("marks.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "Rahul 88\n");
12 fprintf(fp, "Priya 95\n");
13 
14 fclose(fp);
15 printf("Data written successfully\n");
16 return 0;
17}
Output
Data written successfully

2. Write a String Using fputs()

Use fputs() when you want to write a string. It does not add a new line automatically, so include \n if you need one.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("message.txt", "w");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fputs("Welcome to C programming!\n", fp);
12 fclose(fp);
13 
14 printf("Message saved\n");
15 return 0;
16}
Output
Message saved
📝 Key Takeaways
  • Use fopen() with w mode to write a new file or replace existing contents.
  • fprintf() writes formatted data to a file.
  • fputs() writes a string to a file.
  • Check fopen() for NULL and close the file after writing.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3