Home > Article > Backend Development > Explain the write mode operation of files in C language
A file is a collection of records, or a location on your hard drive that is used to permanently store data.
When the program terminates, the entire data will be lost.
Store data in a file and the data will be retained even if the program terminates.
If you want to enter a large amount of data, it usually takes a lot of time to enter.
We can easily access the contents of the file using several commands.
You can easily move data from one computer to another without making changes.
By using C commands, we can access files in different ways.
File operations in C programming language are as follows:
Statement The syntax of file pointer is as follows:
FILE *File pointer;
For example, FILE * fptr;
The syntax of naming and opening file pointer is as follows -
File pointer = fopen ("File name", "mode");
For example,
FILE *fp; fp = fopen ("sample.txt", "w");
The following is a C program for reading the names and grades of n students and storing them in a file−
Real-time demonstration
#include <stdio.h> int main(){ char name[50]; int marks, i, num; printf("Enter number of students: "); scanf("%d", &num); FILE *fptr; fptr = (fopen("std.txt", "w")); // opening file in write mode if(fptr == NULL){ printf("Error!"); exit(1); } for(i = 0; i < num; ++i){ printf("For student%d</p><p>Enter name: ", i+1); scanf("%s", name); printf("Enter marks: "); scanf("%d", &marks); fprintf(fptr,"</p><p>Name: %s </p><p>Marks=%d </p><p>", name, marks); } fclose(fptr); return 0; }
When the above program is executed, it produces the following result −
Enter number of students: 3 For student1 Enter name: lucky Enter marks: 59 For student2 Enter name: pinky Enter marks: 89 For student3 Enter name: bob Enter marks: 45
The following is used to store the employee details in a file C program that creates and prints this file -
Live Demonstration
#include<stdio.h> int main ( ){ FILE *fp; int eno; char ename[30]; float sal; fp =fopen ("emp.txt", "w"); // opening file in write mode printf ("enter the details of eno, ename, sal:"); scanf ("%d%s%f", &eno, ename, &sal); fprintf (fp, "%d%s%f", eno, ename, sal); fclose (fp); fp = fopen ("emp.txt", "r"); fscanf (fp, "%d%s%f", &eno, ename, &sal); printf ("employee no: = %d</p><p>", eno); printf ("employee name = %s</p><p>", ename); printf ("salary = %f</p><p>", sal); fclose (fp); return 0; }
When the above program is executed, it produces the following result −
enter the details of eno, ename, sal:1 Pinky 34000 employee no: = 1 employee name = Pinky salary = 34000.000000
The above is the detailed content of Explain the write mode operation of files in C language. For more information, please follow other related articles on the PHP Chinese website!