Summary: in this tutorial, you will learn how to write a text file using C standard library functions.
Steps for writing to a text file
To write to a text file, you follow these steps:
- First, open the text file for writing using
fopen()
function with the"w"
mode. - Second, write a text to the text file using the
fprintf()
function. - Third, close the file using the
fclose()
function.
It is important to note that if you use the “w” mode, the fopen()
will delete all contents of the file if the file exists.
C Write Text File Example
The following program illustrates how to use the fprintf()
function to write to a text file:
#include <stdio.h>
int main()
{
char *filename = "test.txt";
// open the file for writing
FILE *fp = fopen(filename, "w");
if (fp == NULL)
{
printf("Error opening the file %s", filename);
return -1;
}
// write to the text file
for (int i = 0; i < 10; i++)
fprintf(fp, "This is the line #%d\n", i + 1);
// close the file
fclose(fp);
return 0;
}
Code language: C++ (cpp)
Write to a text file using the fputc() function
To write a character to a text file, you use the fputc() function. The following program shows how to use the fputc() function to write to a text file:
#include <stdio.h>
int main()
{
char *filename = "alphabet.txt";
// open the file for writing
FILE *fp = fopen(filename, "w");
if (fp == NULL)
{
printf("Error opening the file %s", filename);
return -1;
}
// write to the text file
for (char ch = 'a'; ch < 'z'; ch++)
fputc(ch, fp);
// close the file
fclose(fp);
return 0;
}
Code language: PHP (php)
The program writes the characters from a to z to the alphabet.txt
file. If you execute the program and open the alphabet.txt
file, you’ll see the following content:
abcdefghijklmnopqrstuvwxy
Summary
- Use the
fprintf()
function to write a line of text to the text file. - Use the
fputc()
function to write a single character to a file.
Was this tutorial helpful ?