fopen() for existing file in write mode in C

CServer Side ProgrammingProgramming

fopen() method in C is used to open the specified file.

Let’s take an example to understand the problem

Syntax

FILE *fopen(filename, mode)

The following are valid modes of opening a file using fopen(): ‘r’, ‘w’, ‘a’, ‘r+’, ‘w+’, ‘a+’. For details visit visit C library function - fopen()

fopen() for an existing file in write mode

If the file to be opened does not exist in the current directory then a new empty file with write mode is created.

If the file to be opened exists in the current directory and is open using ‘w’ / ‘w+’, the contents will be deleted before writing.

Example

Program to illustrate the working of our solution

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "w");
   if (opFile == NULL){

      puts("Couldn't open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

Output

Write operation successful

Initial contents of the file − C programming language

Contents after append operation − include help 

The write operation does its work but deletes all the contents the were present in the file before the write operation is performed. To tackle this, the C programming language has been updated to two different approaches which the programmer can use based on the requirement of the program.

  • ‘a’ (append) mode − this mode appends the new contents at the end of the contents written in the file.

  • ‘wx’ mode − this will return NULL if the file already exists in the directory.

Example

Program to illustrate write operation on existing file using ‘a’ mode

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "a");
   if (opFile == NULL){

      puts("Couldn't open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

Output

Write operation successful

Initial contents of the file − C programming language

Contents after append operation − C programming language includehelp

Example

Program to illustrate write operation on existing file using ‘wx’ mode

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "wx");
   if (opFile == NULL){

      puts("Couldn't open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

Output

Write operation successful
raja
Updated on 01-Feb-2022 08:35:23

Advertisements