In the world of programming, writing to a text file is a fundamental skill that allows you to store and manipulate data efficiently. Whether you’re building a data logging system, generating reports, or simply saving user input, knowing how to write to a text file is essential. In this blog post, we will explore how to write to a text file in the C programming language.
This is a C program that opens a file named “memo.txt” in write mode (‘w’) using the fopen function. If the file could not be opened, the program prints an error message and returns 1. Otherwise, it writes three lines of text to the file using the fprintf function, and then closes the file using fclose. Finally, the program returns 0 to indicate successful execution.
#include <stdio.h>
int main()
{
char* filename = "memo.txt";
/* Open the specified file in write mode 'w' */
FILE* fptr = fopen(filename, "w");
if(fptr == NULL)
{
printf("Error: could not open file '%s'.\n", filename);
return 1;
}
/* Write some lines of text to the file */
fprintf(fptr, "Line 1\n");
fprintf(fptr, "Line 2\n");
fprintf(fptr, "Line 3\n");
/* Close the file */
fclose(fptr);
printf("Text written to file '%s'.\n", filename);
return 0;
}
Overall, the program creates a new text file and writes some lines of text to it. If the file already existed, its contents would be overwritten by the new data written to it. I hope that’s been informative to you. If you wish to learn more about C, please subscribe to our newsletter today and continue your C learning journey with us!