File Handling in C

File Handling in C Program with Examples

In this article, I am going to discuss File Handling in C Program with examples. Please read our previous article where we discussed Dynamic Memory Management in C. As part of this article, we are going to discuss the following pointers in detail which are related to File Handling in C Program.

  1. What is File?
  2. Why files are needed?
  3. Types of Files
  4. File Modes
  5. File Operations in C
  6. Program: For reading data from files
  7. Program: For Reading a line from a file and display it
  8. Program: To reverse the string data present in a file
  9. Program: Find and Update (or Replace) a character
  10. Program: Encoding and Decoding
  11. Program: Operations on Audio File
  12. Program: combine two or more audio files together
What is File?

A file is the name of a physical memory location in the secondary storage area. The file contains a sequence of bytes of data in the secondary storage area in the form of an unstructured manner. In the implementation, when we required to interact with the secondary storage area, then recommended going for file operations. By using files, primary memory-related data can be sent to the secondary storage area and secondary storage area information can be loaded to primary memory.

In ‘C’ programming language, IO Operations are classified into two types:

  1. Standard IO Operations
  2. Secondary IO Operations

When we are interacting with Secondary IO devices, then it is called as Secondary IO Operations. Standard IO related and Secondary IO related, all predefined functions are declared in stdio.h only.

Why files are needed?

The entire data is lost, when a program is terminated. Storing the data in a file will preserve your data once the program is terminating. It will take a lot of time to enter them a large number of data. However, if you’ve got a file containing all the information, you’ll easily access the contents of the file using a few commands in C. Without any prior changes, you can easily move your data from one computer to another.

Types of Files

When handling files, there are two sorts of files you ought to know about:

  1. Text files
  2. Binary files
Text files

Text files are the normal .txt files. You can easily create text files using any simple text editors like Notepad. When you open those files, you will see all the contents within the file as plain text. You can easily edit or delete the contents. They take minimum effort to for easily readable, and supply the smallest amount of security and takes bigger space for storing. In the Text files, data is represented with the help of ASCII values, i.e., .txt, .c, .cpp

Binary files

Binary files are mostly the .bin files on your computer. Instead of storing data in plain text, they store it within the binary form (0’s and 1’s). They can hold a better amount of knowledge, aren’t readable easily, and provides better security than text files. In binary Files, data is represented with the help of byte, i.e., .exe, .mp3, .mp4, .jpeg

Points to Remember:
  1. To specify that a given file is being opened or create in “text mode” then append “t” to the string mode. Examples: rt, wt, at, rt+, wt+, at+
  2. To specify the binary mode, append “b” to the end of the string mode. Example: rb. Wb, ab, r+b, w+b, a+b
  3. “fopen” and “fsopen” also allow that “t” or “b” to be inserted between the letter and the ‘t’ character in the string. Example: rt+ is equivalent to r+t.
  4. If “t” or “b” is not giving in the string, the mode is governed by “f” mode, if “f” mode is set to O_BINARY, files are opened in BINARY mode.
  5. If “f” mode is set to O_TEXT, they are opened in text mode. These constants are defined in fcntl.h
File Operations

In C, you’ll perform four major operations on files, either text or binary:

  1. Creating a new file
  2. Opening an existing file
  3. Closing a file
  4. Reading from a file and writing information to a file
Example:
#include<stdio.h>
#include<dos.h>
#include<stdlib.h>
int main()
{
 FILE* fp;
 fp = fopen("F:\1.txt","w");
 if(fp == NULL)
 {
  printf("\n Unable to create File");
  return EXIT_FAILURE;
  
 }
 fprintf(fp,"Welcome");
 fprintf(fp,"\n%d HELLO WORLD %f", 100, 12.50);
 fclose(fp);
 return EXIT_SUCCESS;
}

Output

File Handling in C

Points to Remember:
  1. When we are opening a file, two parameters must be passed: Path and Mode
  2. The file may open or may not open. If open, then it returns ADDRESS. If not, then it returns NULL.
  3. stdio.h provides a standard IO related predefined function prototype.
  4. conio.h provide console related predefined function prototype.
  5. FILE is a predefined structure that is available in stdio.h. By using the FILE structure, we can handle file properties. The size of the FILE structure is 16 bytes.
  6. fp is a variable of type FILE*, which maintains the address of FILE. The size of fp is 2 bytes because it holds an address.
fopen()

It is a predefined function, which is declared in stdio.h, by using this function we can open a file in a specific path with specific mode. It requires two arguments of type const char*. On success, fopen() returns FILE*, on failure returns NULL. Generally, fopen() is failed to open FILE in the following cases:

  1. The path is incorrect.
  2. Mode is incorrect
  3. Permissions are not available
  4. Memory is not available

Syntax: FILe *fopen(const char* path, const char* mode);

fprintf()

By using this predefined function, we can write the content in the file. fprintf() can take any number of arguments but the first argument must be FILE* and remaining arguments are of any path.

Syntax: int fprintf(FILE* stream, const char*path,…..);

fclose()

By using this predefined function, we can close the file after saving data. fclose() requires one argument of type FILE* and returns an int value.

Syntax: int fclose(FILE* stream);

File Modes

Always FILE modes will indicate that for what purpose file need to be open or create. File modes are classified into three types:

  1. Write
  2. Read
  3. Append

Depending on operations, file modes are classified into 6 types:

  1. Write(w): Create a file for writing, if the file already exists, then it will override (old file is deleted and a new file is created). In “w” mode, the file exists or not, always a new file is constructed.
  2. Read(r): Open an existing file for reading, if file not exists then fopen() returns NULL. When we are working with “r” mode, if the file doesn’t exist, a new file is not constructed.
  3. Append(a): Open an existing file for appending (write the data at end of file) or create a new file for writing if it doesn’t exist. When we are working with “a”, if file doesn’t exist, then only a new file is constructed.
  4. w+ (write and read): Create a file for update i.e. write and read, if the file already exists then it will override. In w+ mode, if the file is available or not, always a new file is constructed.
  5. r+ (read and write): Open an existing file for update I.e. read and write. Generally, “r+” mode is required, when we need to update existing information. In “r+” mode, if the file doesn’t exist, a new file is not constructed.
  6. a+ (w+ and r+): Open an existing file for update or create a new file for update. By using a+ mode, we can perform random operations.
Program: For reading data from files
#include<stdio.h>
#include<stdlib.h>
int main()
{
 FILE* fp;
 char ch;
 fp = fopen("F:\1.txt","r");
 if(fp == NULL)
 {
  printf("\n File not Found");
  return EXIT_FAILURE;
 }
 while(1)
 {
  fscanf(fp,"%c",&ch);
  if(feof(fp))	//if(ch == EOF)
  break;
  printf("%c",ch);
 }
 fclose(fp);
 return EXIT_SUCCESS;
}

Output

reading data from files in C language

fscanf()

It is a predefined function that is declared in stdio.h, by using this function, we can read the data from a file. fscanf() can take any number of arguments bust first argument must be and remaining arguments should be scanf() function format. When we are working with fscanf() function, it can read the entire content of the file except.

Syntax: int fscanf(FILE* stream, const char” format,…..);

feof()

By using this function, we can find the end of the character position. It requires one argument of type FILE* and returns an int value. When the file pointer is pointing to EOF character then it returns a non-zero value, if it is pointing to other then EOF character then it returns zero.

Syntax: int feof(FILE* stream);

fgetc()

It is a predefined unformatted function that is declared in stdio.h, by using this function we can read the data from a file including EOF character also. It returns an int value i.e. ASCII value of a character.

Syntax: int getc(FILE* stream);

Program: Reading a line from a file and display it
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen("F:\1.txt", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);

    return 0;
}

Output

Reading a line from a file and display it

Program :
#include<stdio.h>
#include<conio.h>
int main()
{
 FILE* fp;
 char path[50];
 char str[50];

 fprintf(stdout, "Enter a file path : ");
 gets(path);
 fp = fopen(path,”a");
 if(fp == NULL)
 {
  fprintf(stderr, "Unable o create file");
  getch();
  return 1;
 }
 printf("Enter a String : ");
 fflush(stdin);
 gets(str);
 fputs(str, fp);
 fclose(fp);
 return 0;
}

Output

Reading a file and display it in C Program

1.txt

Why files are needed in C?

Delay

It is a predefined function that is declared in dos.h. By using this function, we can suspend the program from execution. delay() function requires one argument of type unsigned integer i.e. milliseconds value. By using delay(), we can suspend the program for a maximum of 1 sec and a minimum of 5 sec.

Syntax: void delay(unsigned milliseconds);

sleep()

It is a predefined function that is declared in dos.h. By using this function, we can suspend the program execution sleep() function requires one argument of type unsigned integer seconds format data.

Syntax: void sleep(unsigned seconds);

stdout: It is a global pointer variable that is defined in stdio.h. By using this global pointer, we can handle the standard output buffer.

stdin: By using this global pointer, we can handle the standard input buffer.

stderr: By using this global pointer, we can handle standard IO related errors. When we are working with stderr, it will redirect the data back to stdout.

stdprn: By using this global pointer, we can handle the printer.

fseek()

By using this predefined function, we can create the movement in the file pointer. fseek() requires three arguments of type FILE*, long integer and an integer type.

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

Where stream will provide file information, Offset is the number of bytes, and whence value is file pointer location. The whence value can be recognized by using the following constant values:

  1. SEEK_SET: This constant will pass the file pointer to the beginning of the file.
  2. SEEK_CUR: This constant will provide the constant position of the file pointer.
  3. SEEK_END: This constant value will send the file pointer to the end of the file.

These constant values can be recognized using INTEGER values also.

  1. SEEK_SET value is 0.
  2. SEEK_CUR value is 1.
  3. SEEK_END value is 2.
rewind()

By using this predefined function, we can send the control to the beginning of the file. rewind() requires one argument of type FILE*.

Syntax : void rewind(FILE* stream);

The behavior of rewind() is similar to – fseek(FILE*, O, SEEK_SET)

ftell()

By using this predefined function, we can find the size of the file. ftell() requires one argument of type FILE* and returns a long integer value. Generally, ftell() returns file pointer position, so if the file pointer is pointing to end of character then it is equal to the size of the file.

Syntax: long ftell(FILE* stream);

remove()

By using this predefined function, we can delete two files permanently from hard disk. remove() requires one argument of type constant char* and returns an int value.

Syntax: int remove(const char* filename);

rename()

By using this predefined function, we can change the name of an existing file. rename() function requires two types of arguments of type const char and returns an int value.

Syntax: int rename(const char* oldname, const char* newname);

Program: To reverse the string data present in a file
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
 FILE* fp;
 char path[50];
 long int fsize, i=0;
 char* str;
 char ch;
 printf("Enter a file path :");
 gets(path);
 fp = fopen(path,"rt");
 if(fp == NULL)
 {
  printf("\n File not found");
  return 1;
 }
 fseek(fp, 0, SEEK_END);
 fsize = ftell(fp);
 fseek(fp, 0, SEEK_SET);
 str = (char*)calloc(fsize, sizeof(char));
 while(1)
 {
  ch = fgetc(fp);
  if(feof(fp))
  break;
  str[i++] = ch;
 }
 str[i] = '\o';
 fclose(fp);
 remove(path);
 strrev(str);
 fp = fopen(path,"wt");
 fputs(str, fp);
 fclose(fp);
 free(str);
 str = NULL;
 return 0;
}

Output

reverse the string data present in a file in C

1.txt

File Handling in C

Program: Find and Update (or Replace) a character
#include<stdio.h>
#include<stdlib.h>
int main()
{
 FILE* fp;
 char path[50];
 char ch, sch, dch;
 printf("Enter a file path : ");
 gets(path);
 fp = fopen(path,"rt+");
 if(fp == NULL)
 {
  printf("File not found");
  return 1;
 }
 printf("\n Enter a source character(s) : ");
 fflush(stdin);
 sch = getchar();
 printf("\n Enter a destination character(D) : ");
 fflush(stdin);
 dch = getchar();
 while(1)
 {
  ch = fgetc(fp);
  if(ch == EOF)
  break;
  if(ch == sch)
  {
   fseek(fp, -1, SEEK_CUR);
   fprintf(fp,"%c",dch);
   fseek(fp,0,SEEK_CUR);
  }		
 }
 fclose(fp);
 return 0;
}

Output

Program to Find and Update (or Replace) a character in C

2.txt

C File Handling

Program: Encoding and Decoding
#include<stdio.h>
#include<conio.h>
int main()
{
 FILE* fp;
 int flag, code =0;
 char path[30];
 char ch;
 printf("Enter a file path : ");
 gets(path);
 fp = fopen(path, "r+");
 if(fp == NULL)
 {
  printf("\n File not found");
  getch();
  return 1;
 }
 do
 {
  printf("\n 1 for ENCODE : ");
  printf("\n 2 for DECODE : ");
  scanf("%d",&flag);
 }
 while(flag != 1 && flag!=2);
 if(flag == 1)
 code = 40;
 else
 code = -40;
 while(1)
 {
  ch = fgetc(fp);
  if(ch == EOF)
  break;
  if(ch!='\n'&&ch!='\r')
  {
   fseek(fp,-1,SEEK_CUR);
   fprintf(fp,"%c",ch+code);
   fseek(fp,0,SEEK_CUR);
   
  }
 }
 fclose(fp);
 return 0;
}

Output

Encoding and Decoding in C Language

2.txt (after Encoding)

C File Handling Examples

2.txt (after Decoding)

File Handling Examples in C

Program: Operations on Audio File
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
# define f1 "F:\part1.mp3"
# define f2 "F:\part2.mp3"
# define f3 "F:\part3.mp3"
# define f4 "F:\part4.mp3"
int main(void)
{
 FILE* sfp;
 FILE* dfp;
 char spath[30];
 char dpath[4][30] = {f1, f2, f3, f4};
 long int fsize =0, nb =0;	// nb is number of bytes
 int i=0;
 char ch;
 printf("\n Enter sfp path : ");
 gets(spath);
 if (sfp == NULL)
 {
  printf("\n %s NOT FOUND",spath);
  return EXIT_FAILURE;
  
 }
 fseek(sfp, 0, SEEK_END);
 fsize = ftell(sfp);
 rewind(sfp);
 dfp = fopen(dpath[i],"wb");
 if(dfp ==NULL)
 {
  fclose(sfp);
  printf("\n%s Unable to create");
  return EXIT_FAILURE;
 }
 while(1)
 {
  ch = fgetc(sfp);
  if(feof(sfp))
  break;
  fprintf(dfp,"%c", ch);
  ++nb;
  if(nb = fsize/4 && i != 3)
  {
   fclose(dfp);
   nb = 0;
   ++i;
   dfp = fopen(dpath[i],"wb");
   if(dfp == NULL)
   {
    printf("\n %s Unable to create", dpath[i]);
    fclose(sfp);
    return EXIT_FAILURE;
   }
  }
 }
 fclose(sfp);
 fclose(dfp);
 return EXIT_SUCCESS;
}

Output

Operations on Audio File in C

Program: combine two or more audio files together
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
# define f1 "F:\part1.mp3"
# define f2 "F:\part2.mp3"
# define f3 "F:\part3.mp3"
# define f4 "F:\part4.mp3"
int main(void)
{
 FILE* sfp;
 FILE* dfp;
 char dpath[30];
 char spath [4][30]= {f1, f2, f3, f4};
 int i=0;
 char ch;
 printf("\n enter dfp path : ");
 gets(dpath);
 dfp = fopen(dpath,"wb");
 if(dfp == NULL)
 {
  printf("\n%sUnable to create", dpath);
  return EXIT_SUCCESS;
 }
 for(i=0; i<4; i++)
 {
  sfp = fopen(spath[i],"rb");
  if(sfp == NULL)
  {
   fclose(dfp);
   printf("\n%s Not Found", spath[i]);
   return EXIT_FAILURE;
  }
  while(1)
  {
   ch = fgetc(sfp);
   if(feof(sfp))
   break;
   fprintf(dfp,"%c",ch);
  }
  fclose(sfp);
 }
 fclose(dfp);
 return EXIT_SUCCESS;
}

Output

combine two or more audio files together in c

In the next article, I am going to discuss Error Handling in C Program with Examples. Here, in this article, I try to explain File Handling in C Program with Examples. I hope you enjoy this File Handling in C Program article. I would like to have your feedback. Please post your feedback, question, or comments about this File Handling in C Program article.

Leave a Reply

Your email address will not be published. Required fields are marked *