How to Write Multiple Lines to File in C
- 1). Open your C source file in an Editor, such as Microsoft Visual Studio Express.
- 2). Include the "stdio" header file at the top of your file, by adding the code "#include <stdio.h>."
- 3). Open the file you want to write to by adding the code "FILE *my_file; my_file = fopen("nameoffile.txt", "a");." The "a" attribute signifies that text is appended to the end of the file.
- 4). Write multiple lines to the file with repeated calls of the "fputs" function by adding the code:
fputs("line1\n", my_file);
fputs("line2\n", my_file);
This outputs "line1" and "line2" to your file. The "\n" character signifies a new line. Alternatively, you can use the "fprintf" function with the code "fprintf(my_file,"%s","text here");." - 5). Close the C file by adding the code "fclose(my_file);."
- 6). Save the C source file, compile and run the program to write to your file.
Source...