This is a file tutorial where we will write a C program to create a file and write into it. Before that, you may go through the following C topics.
Explanation: The program is based on the file system in C. The program opens the file system in writing mode, hence the “w”. If the file is not present with the name provided then the program will create a file on the same directory.
The program will check if the file is Null or not. If not then, it will ask the user to enter data which later will be inserted into the file. Let us go through the program.
Program to write into a file in C
FILE * fptr;
fptr = fopen("test.txt", "w");
if (fptr == NULL)
printf("Enter the data: \n");
fgets(data, 100, stdin);
fputs(data, fptr); //writing to a file
printf("\nFile created and saved successfully.");
After successful execution of the program, a file named “test.txt” will be created (if not already created) in the same directory where you have stored the source code file. Open that file and you will see the data that you wrote on the program will be present there in the following way.
This is simple2code.com