Select Page

C – File I/O – GeeksforGeeks

Rashi Garg
Published: November 4, 2022

In this article you will learn what are files in C, why they are needed, and how to handle standard I/O in C with the help of different C functions like fopen(), fclose(), fprintf(), fscanf(), getc(), putc(), getw(), fseek(), etc. A file represents a sequence of bytes regardless of being a text file or a binary file.

A file is used to store huge data. C provides multiple file management functions like file creation, opening and reading files, Writing to the file, and closing a file. The file is used to store relevant data and file handling in C is used to manipulate the data.

Types of Files

There are mainly two types of files that can be handled using File Handling in C:

1. Text Files: These are simple text files that are saved by the (.txt) extension and can be created or modified by any text editor. Text file stores data in the form of ASCII characters and are used to store a stream of characters.

2. Binary Files: It is stored in binary format instead of ASCII characters. Binary files are normally used to store numeric Information (int, float, double). Here data is stored in binary form i.e, (0’s and 1’s).

Different Operations Which can be performed on a file is:

  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w+”).
  2. Opening an existing file (fopenopen).
  3. Reading from file (fscanf or fgets).
  4. Writing to a file with fprintf or fputs.
  5. Moving file pointer associated with a given file to a specific position. (fseek, rewind).
  6. Closing a file (close).

For performing operations on the file, a special pointer called File pointer is used which can be declared as:

FILE file_ptr;

We can open the file as

file_ptr = fopen(“fileName.txt”, “w”);

The second parameter i.e, “w” can be changed according to the table below:

Opening ModesDescription
rSearches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ) then it returns NULL.
rb Open for reading in binary mode. If the file does not exist then fopen( ) will return NULL.
wSearches file. Contents are overwritten if the file exists. A new file is created if the file doesn’t exist. Returns NULL, if unable to open the file.
wbOpen for writing in binary mode. Its contents are overwritten if the file exists, else the file will be created. 
aSearches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
ab Open for append in binary mode. Data is added to the end of the file. A file will be created if it does not exist.
r+Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. If it is unable to open the file it Returns NULL.
rb+ Open for both reading and writing in binary mode. fopen( ) returns NULL if the file does not exist.
w+Searches file. Its contents are overwritten if the file exists. A new file is created if the file doesn’t exist. Returns NULL, if unable to open the file.
wb+Open for both reading and writing in binary mode. Contents are overwritten if the file exists. It will be created if the file does not exist.
a+Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
ab+Open for both reading and appending in binary mode. A file will be created if the file does not exist.

If you want to handle binary files then access modes like “rb”, “wb”, “ab”, “rb+”, r+b”, “wb+”, “w+b”, “ab+”, “a+b” will be used mostly.

Opening or Creating a file in C

To perform the opening and creation of a file in c we can use fopen() function which comes under stdio.h header file.

Syntax:

p = fopen(“fileopen”, “mode”);

Example:

p = fopen(“Hello.txt”, r);

Reading and Writing to a text file in C

fprintf() and fscanf() are used to read and write in a text file in C programming. They expect a pointer to the structure FILE since they are file versions of print() and scanf().

C

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  char str[20];

  FILE* ptr;

  

  ptr = fopen("Hello.txt", "w+");

    

  if (ptr == NULL) 

  {

    printf("Error Occured While writing to a text file !");

    exit(1);

  }

  

  printf("Enter String ");

  fgets(str, 80, stdin);

  

  fputs(str, ptr);

  fclose(ptr);

  

  return 0;

}

Output:

Write to a File

 

The above program takes a string from a user and stores it in text_file.text.After compiling this program a text file named temp_text.txt will be created in the C_Program folder. Inside the file, we can see the string that we entered.

Below is the C program to read the contents from the file:

C

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  char str[80];

  FILE* ptr;

  

  ptr = fopen("Hello.txt", "r");

  

  if (ptr == NULL) 

  {

    printf("Error While opening file");

          

    

    

    exit(1);

  }

    

  if(fgets(str, 80, ptr) != NULL)

  {

    puts(str);

  }

  fclose(ptr);

  

  return 0;

}

Output:

Readfromfile

 

Reading and Writing to a Binary File

fread() is used to read from a binary file and fwrite() is used to write to a file on the disk.

1. Writing to a Binary File

fwrite() function takes four arguments address of data, size of the data which is to be written on the disk, number of data types, and a pointer to the file where we want to write.

Syntax:

fwrite(const void *ptr,size_of_elements,number_of_elements, FILE *a_file);

Below is the C program to write to a binary file:

C

#include <stdio.h>

#include <stdlib.h>

  

struct Num 

{

  int n1, n2;

};

  

int main()

{

  int n;

  struct Num obj;

  FILE* fptr;

  if ((fptr = fopen("temp.bin", "wb")) == NULL) 

  {

    printf("Error! opening file");

          

    

    

    exit(1);

  }

      

  for (n = 1; n < 10; n++) 

  {

    obj.n1 = n;

    obj.n2 = 12 + n;

    fwrite(&obj, sizeof(struct Num), 

           1, fptr);

  }

    

  fclose(fptr);

  return 0;

}

Output: 

Writetobinary file

 

Explanation:  In the above program, we are creating a new file with the name GFG.bin. Structure with the name Num has been declared with two numbers – n1, n2 and created an object with the name obj. In for loop, we are storing values in the file with the help of fwrite() function. The first parameter takes the address of obj and the second takes the size of the defined structure Num.

As we have only inserted one instance of obj then the third parameter will be 1. fptr will be pointing to the file where data is stored. And at last, we have closed the file.

2. Reading from a Binary File

fread() function also takes four arguments that are similar to fwrite() function in C Programming.

Syntax:

fwrite(const void *ptr,size_of_elements,number_of_elements, FILE *a_file);

Below is the C program to read from a binary file:

C

#include <stdio.h>

#include <stdlib.h>

struct Num 

{

    int n1, n2;

};

  

int main()

{

  int n;

  struct Num obj;

  FILE* fptr;

  if ((fptr = fopen("temp.bin", "rb")) == NULL) 

  {

    printf("Error! opening file");

          

    

    

    exit(1);

  }

      

  

  

  for (n = 1; n < 10; ++n) 

  {

    fread(&obj, sizeof(struct Num), 1, fptr);

    printf("n1: %d\tn2: %d\n", obj.n1, obj.n2);

  }

    

  fclose(fptr);

  return 0;

}

Output:

Read from binary file

 

Explanation: In the above program, we have read the same file GFG.bin and are looping through records one by one. We read a single Num record of Num size from the file pointed by *fptr into the structure Num. We’ll get the same record that we inserted in the previous program. 

Moving File Pointers to Specific Positions

fseek() and rewind() are the two methods in C programming that can be used to move the file pointer.

1. fseek() in C Programming

fseek() function is used to set the file pointer to the specified offset and write data into the file.

Syntax:

int fseek(FILE *stream, long int offset, int whence);

Here,

  • whence can be SEEK_SET, SEEK_CUR and SEEK_END.
  • SEEK_END: It denotes end of the file.
  • SEEK_SET: It denotes starting of the file.
  • SEEK_CUR: It denotes the file pointer’s current position.

Below is the C program to implement fseek():

C

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  char str[80];

  FILE* ptr;

  

  ptr = fopen("Hello.txt", "w+");

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fseek(ptr, 11,  SEEK_SET);

  fputs("Programming  ", ptr);

  fclose(ptr);

    

  ptr = fopen("Hello.txt", "r+");

  if(fgets(str, 80, ptr) != NULL)

  {

    puts(str);

  }

  

  fclose(ptr);

  return 0;

}

Output:

fseek in C

 

2. rewind() in C

rewind() function sets the file pointer to the beginning of the file. 

Syntax:

void rewind(FILE *stream);

Below is the C Program to implement rewind():

C

#include <stdio.h>

#include <stdlib.h>

  

int main()

{

  char str[200];

  FILE* ptr;

  

  ptr = fopen("Hello.txt", "w+");

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fclose(ptr);

    

  ptr = fopen("Hello.txt", "r+");

  if(fgets(str, 200, ptr) != NULL)

  {

    puts(str);

  }

  rewind(ptr);

  if(fgets(str, 200, ptr) != NULL)

  {

    puts(str);

  

  

  fclose(ptr);

  return 0;

}

Output:

Rewind in c

 

Source: www.geeksforgeeks.org