Writing to a file is a basic programming requirement. All information of a running program is generally stored in the physical memory or RAM. They are lost with the termination of the program. If you need to persist some information, you need to store it in some persistent storage like a disk. Writing to a file is a very common way of persisting data.
For example, when we write something on a notepad application and save that to a file. Whatever we write is basically saved to the file in text format. But when we draw something in the paint application, that can also be saved to a file in a complicated binary format.
Here we’ll see how a C program can write text to a file.
Logic to Write to a File
- Declare a file pointer variable, FILE *fp.
- Open a file using the fopen() function. This function takes the file name as input and the open mode. Specify the open mode as “w” for writing. The file specified by the name will be created.
- Write to files using functions like fprintf(), fputs() etc.
- Close the file using the fclose() function.
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LEN 1024
int main() {
char name[MAX_LINE_LEN];
int age;
char file_name[MAX_LINE_LEN];
FILE *fp;
/*Taking your name and age as input. These will be saved in a file...*/
printf("Your name: ");
gets(name);
printf("Your age: ");
scanf("%d", &age);
/*Flushing extra new line left over by previous operation...*/
getchar();
/*Taking the file name as input...*/
printf("Enter the file name to save: ");
gets(file_name);
/*Opening the file...*/
fp = fopen(file_name, "w");
/*File open operation failed.*/
if (fp == NULL) return -1;
/*Writing your name and age into the file...*/
fprintf(fp, "Your name: %s\n", name);
fprintf(fp, "Your age: %d\n", age);
/*Closing the file...*/
fclose(fp);
printf("Your name and age are saved to the file %s. Open and check.\n", file_name);
return 0;
}
This program first takes a string, name, and an integer, age, as input. Then it takes the file name to save this information.
File with this name is opened in writing mode. The name and age are written to the file using the fprintf() function. At the end the file is closed.
Output of the program:
$ cc test.c -o test
$ ./test
Your name: Charges Babbage
Your age: 85
Enter the file name to save: info.txt
Your name and age are saved to the file info.txt. Open and check.
We can see a new file with the name info.txt is created in the same location we ran the program from. We can see the content written in the file.
$ cat info.txt
Your name: Charges Babbage
Your age: 85