Filing in C (part 2)
Submitted by Muzammil Muneer on Friday, September 26, 2014 - 09:30.
Writing in a File
In this part you will learn: 1. C syntax 2. Filing 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 Basic Step: Open Dev C++ then File > new > source file and start writing the code below.- #include<stdio.h>
- #include<conio.h>
- struct student
- {
- int age;
- int gpa;
- char name[25];
- };
- int main()
- {
- char filename[25];
- student s;
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
Output


Add new comment
- 64 views