C Programming Tutorial
About Lesson

C File handling

In this tutorial, we will learn about file handling in C. we will also learn to handle standard I/O in C using fprintf(), fscanf(), fread(), fwrite(), fseek() etc. with the help of examples.


What is file ?

File a collection of bytes which is stored on computer storage devices.

Note : Files are used to store your data even after the termination of the program and we can also move our data from one computer to another computer easily.


Why files are needed?

  • When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates.
  • If you have to enter a large number of data, it will take a lot of time to enter them all.
    However, if you have a file containing all the data, you can easily access the contents of the file using a few commands in C.
  • You can easily move your data from one computer to another without any changes.

Types of Files

When dealing with files, there are two types of files you should know about:

  1. Text files
  2. Binary files

Text files

Text files contain ASCII codes of digits, alphabetic and symbols.

These files contain plain text which is easily editable, readable and deleteable content.

These files are less secure and takes more space as compare to binary file.

These files have extension .txt and can be created easily with any text editor.


Binary files

Binary files contain collection of bytes (0’s and 1’s).

These files contain binary numbers which is not easily editable and readable content.

These files are highly secure and takes less space as compare to text file.

These files have extension .bin.


Basic File Operations

We can perform some basic operations on any file in C programming :

  1. Opening/Creating a file
  2. Closing an existing file
  3. Reading a file
  4. Writing information to a file

Working with files

In C programming, we have to declare a pointer of type FILE to work with files and establish communication between the file and the program.

FILE *filePointerName;

Opening/Creating a file

In C programming, the fopen() function is used to open the file pointed by the pointer.

Syntax

ptrName = fopen("fileaddress","mode");

Example

fopen("C:\\document\\file.txt","w");
fopen("C:\\document\\oldfile.bin","rb");

Closing a File

In C programming, the fclose() functionis used to close the file pointed by the pointer.

Syntax

fclose(pointerName);

Here, pointerName is a file pointer associated with the file which we want to close.


Reading a file

In C programming, the fgets() function is used to read a file pointed by the pointer line by line.

Syntax

fgets(buffer, size, pointerName);

Here,
    buffer => buffer to put data in
    size => size of the buffer
    pointerName => file pointer


Writing information to a file

In C programming, the fprintf() function is used to write string into a file pointed by the pointer.

Syntax

fprintf(pointer, "text Data", variable_name);

Here, text Data is the string we want to write into the file pointer by the pointer.


Different Mode of Operations to perform on a Text File

Different Mode of Operation for a Text File
Mode Meaning
r Open a file in read mode .
It sets pointer to the first character in the file.
w Open a file in write mode and overwrite data of the file.
Return null if file could not be opened.
a Open a file in append mode.
data is added to the end of the file.
r+ or w+ Open a file in both read and write mode .
It set the pointer to the first character in the file.
a+ Open a file in both read and append mode.
It sets the pointer to the first character in the file.
It can’t modify existing contents.

Example : Open, Write and Close a text file

#include <stdio.h>
#include <stdlib.h>
int main() {
  char grade;
  FILE *file_pointer;
  fptr = fopen("C:\\myfile.txt","w"); //opening myfile.txt
  if(filepointer == NULL) {
  printf("Error! Could not open myfile.txt");
  exit(1);
  }
  printf("Enter text to input in file : ");
  scanf("%c",&grade);
  fprintf(filepointer,"%c",grade);
  fclose(filepointer);
  return 0;
}

Here, This program creates a file myfile.txt and then take a character from the user and stores in the file myfile.txt. When we open the file, we can see the character you entered.


Example : Open, Read and Close a text file

#include <stdio.h>
#include <stdlib.h>
int main() {
  char data[30];
  FILE *filepointer;
  filepointer = fopen("C:\\myfile.txt","r");
  if (filepointer == NULL){
    printf("Error! Could not opening myfile.txt");
  return 1;
  }
  printf("Reading the file myfile.txt");
  while(fgets(data, 50, filepointer) != NULL)
    printf("%s", data);
  printf("Closing myfile.txt");
  fclose(filepointer);
  return 0;
}

Here, This program reads the string present in myfile.txt and print it onto the screen.


Writing to a binary file

In C programming, the fwrite() function is used to write into a binary file.

Syntax

fwrite(address, size, numbers, pointer);

Here,

  • address -> Address of data
  • size -> Size of data
  • numbers -> Number of such type of data
  • pointer -> Pointer to the file where you want to write

Reading from a binary file

In C programming, the fread() function is used to read a binary file.

fread(address, size, numbers, pointer);

Here,

  • address -> Address of data
  • size -> Size of data
  • numbers -> Number of such type of data
  • pointer -> Pointer to the file where you want to write

Different Mode of Operations to perform on a Binary File

Different Mode of Operation for a Binary File
Mode Meaning
rb Open a file for reading in binary mode.
wb Open a file for writing in binary mode.
ab Open a file for appending in binary mode.
Data is added to the end of the file.
rb+ or wb+ Open a file for both reading and writing in binary mode.
ab+ Open a file for both reading and appending in binary mode.

Example : Open, Write and Close a Binary file

#include <stdio.h>
#include <stdlib.h>
struct studentData {
  char name[50];
  int age;
  } student;
int main() {
  int n, i, num;
  FILE *filepointer;
  filepointer =   fopen("C:\\student.txt", "wb");
  if(filepointer == NULL) {
    printf("Error opening file\n");
    exit(1);
  }
  printf("Enter the number of records you want to enter: ");
  scanf("%d", &n);
  for(i = 0; i < n; i++) {
    printf("\nEnter details of employee %d \n", i + 1);
    fflush(stdin);
    printf("Name: ");
    gets(student.name);
    printf("Age: ");
    scanf("%d", &student.age);
    num = fwrite(&student, sizeof(student), 1, filepointer);
    printf("Number of items written to the file: %d\n", num);
  }
  fclose(filepointer);
  return 0;
}

Output

Enter the number of records you want to enter: 2
Enter details of employee 1
Name: Allen
Age: 16
Number of items written to the file: 1
Enter details of employee 2
Name: Otish
Age: 34
Number of items written to the file: 1

Note : The fflush() is used to flush the output buffer of the stream. It return 0 if it is successful.


Example : Open, Read and Close a Binary file

#include <stdio.h>
#include <stdlib.h>
struct studentData {
  char name[50];
  int age;
  } student;
int main() {
  int n, i, num;
  FILE *filepointer;
  filepointer = fopen("C:\\student.txt", "wb");
  if(filepointer == NULL) {
    printf("Error opening file\n");
    exit(1);
  }
while(fread(&student, sizeof(student), 1, filepointer) == 1 ) {
    printf("Name: %s \n", student.name);
    printf("Age: %d \n", student.age);
}
  fclose(filepointer);
  return 0;
}

Output

Name: Rob
Age: 19
Name: Jake
Age: 14

fseek() Function

The fseek() function is used to access a particular record of data in a file at a specific position.

Syntax

fseek(pointer, offset, whence);

Here,

  • pointer -> File pointer
  • offset -> Characters to be offset
  • whence -> Current file pointer position from where offset is added

 

Whence

Whence sets the file current file pointer position with respect to where the file pointer is present.

whence in fseek()
Whence Meaning
SEEK_SET Moves file pointer position to the beginning of the file
SEEK_CUR Moves file pointer position to given location
SEEK_END Moves file pointer position to the end of file

Example 5: fseek()

#include <stdio.h>
#include <stdlib.h>
int main() {
  // Open the file for writing
  FILE* filepointer = fopen("introduction.txt", "a");
  // Move the pointer to the end of the file
  fseek(filepointer, 0, SEEK_SET);
  char text[] = "Hello Everyone,\n";
  // Write to the file using fwrite()
  fwrite(text, sizeof(buffer), sizeof(char), filepointer);
  printf("Appended:%s to the file!\n", text);
  // Close the file
  fclose(filepointer);
  return 0;
}

Output

Hello Everyone
My name is Jack.
My age is 21.

 

error: Content is protected !!