Summary: in this tutorial, you will learn how to write a text file using C standard I/O functions.
C Write Text File Steps
The following illustrates the steps of writing text into a text file line by line:
- First, open the file for writing using fopen() function with mode ‘w’. It is important to note that in this mode the file content is deleted and the file is overwritten if the file already exists.
- Second, use function fprintf() to write text to the file stream.
- Third, use function fclose() to close the file.
C Write Text File Example
The following program writes 10 lines of text into a text file named 1.txt in the c:\temp folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /* * Author: zentut.com * Description: C Write text file demo */ #include <stdio.h> #define LEN 256 int main () { FILE * fp; int i; /* open the file for writing*/ fp = fopen ("c:\\temp\\1.txt","w"); /* write 10 lines of text into the file stream*/ for(i = 0; i < 10;i++){ fprintf (fp, "This is line %d\n",i + 1); } /* close the file*/ fclose (fp); return 0; } |
In this tutorial, you’ve learned how to write text into a text file using function fprintf().