Explain write mode operation of files in C language


File is collection of records or is a place on hard disk, where data is stored permanently.

Need of files

  • Entire data is lost when a program terminates.

  • Storing in a file preserves the data even if, the program terminates.

  • If you want to enter a large amount of data, normally it takes a lot of time to enter them all.

  • We can easily access the content of files by using few commands.

  • You can easily move your data from one computer to another without changes.

  • By using C commands, we can access the files in different ways.

Operations on files

The operations on files in C programming language are as follows −

  • Naming the file
  • Opening the file
  • Reading from the file
  • Writing into the file
  • Closing the file

Syntax

The syntax for declaring a file pointer is as follows −

FILE *File pointer;

For example, FILE * fptr;

The syntax for naming and opening a file pointer is as follows −

File pointer = fopen ("File name", "mode");

For example,

FILE *fp;
fp = fopen ("sample.txt", "w");

program1

Following is the C program to read name and marks of n number of students and store them in a file −

 Live Demo

#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
Enter name: ", i+1);       scanf("%s", name);       printf("Enter marks: ");       scanf("%d", &marks);       fprintf(fptr,"
Name: %s
Marks=%d
", name, marks);    }    fclose(fptr);    return 0; }

Output

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

Program2

Following is the C program for storing the details of an employee in a file and to print the same −

 Live Demo

#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
", eno);    printf ("employee name = %s
", ename);    printf ("salary = %f
", sal);    fclose (fp);    return 0; }

Output

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

Updated on: 24-Mar-2021

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements