Writing in a File
In this part you will learn:
1. C syntax
3. Writing to a File
In this tutorial we will learn about filing in C. Filing is a very important tool in C. In this program we will write data in a file. We will take input from the user and write that data in a file whose name will be entered by the user.
Writing in a File
Open Dev C++ then File > new > source file and start writing the code below.
These two are the most common and basic header files. The first one stdio.h is used to grant us most of the basic functions of C like Input and Output functions. The second one conio.h provides us functions like getch() which is used to pause our screen until we press a button.
printf("Enter the name of the file: ");
In this program we are writing a student record in the file. At first we declared a structure. In this structure we declared three variables. A character array for name, an integer for gpa and an integer for age. Then we came in our main function where we declared a character array to store the name of the file that we will take from the user. After taking input from the user we ask the user to input the name , age and gpa.
After taking all the inputs we declared a FILE pointer and assigned it the address of our file. Note that here we wrote “W” after the filename. This “w” means we are opening this file in the write mode.
printf("\nFile cannot be opened.");
Now in this part of the code we wrote a condition that if the file that we are trying to open is accessible or not. If the file is not accessible or the file cannot be opened then the program will give an error. Otherwise the else part will be executed.
In the else part we wrote a function called fprintf(). Function writes data into the file. The first argument that is given to this function is the file name so that it knows where to write the data. Then we place the format specifier just like in the normal printf() function. And then we wrote the name of the variable that we whose value we want to write in the file.
We wrote three fprintf() statements to write all the data that was palced in the structure student. After that we closed the file and ended the program.
Execute > compile
then Execute > run