fopen() for an existing file in write mode in C

CProgrammingServer Side Programming

The function fopen() opens the file pointed by pointer and read or write the file. In the write mode, “w” is used and in the read mode, “r” is used.

When a file exists in the directory, it treats as a new empty file and override the content of file by new data.

Here is the syntax of fopen() in C langauge,

FILE *fopen(const char *filename, const char *access_mode)


filename − The name of file which is to be opened.

acess_mode − The mode to access the file like read or write mode.

Here is an example of fopen() in C language,

Let’s say we have a file “one.txt” with the following content.

This is demo text!
This is demo text!
This is demo text!

Now, let us see the example.


#include <stdio.h>
void main () {
   FILE *f;
   int len;
   f = fopen("one.txt", "r");
   if(f == NULL) {
      perror(“Error opening file”);
   fseek(f, 0, SEEK_END);
   len = ftell(f);
   printf("Size of file: %d bytes", len);


Size of file: 78 bytes

In the above program, a file type pointer variable is declared as f and it is used to open the file named as “one.txt” by using fopen() function.

FILE *f;
int len;
f = fopen("one.txt", "r");
Updated on 26-Jun-2020 07:57:29