File Handling in C Language

What is a 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 were 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 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 terminated. It will take a lot of time to enter 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 editor 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, supply the smallest amount of security, and take 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 created 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 Language with Examples
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 the standard IO Related predefined function prototype.
  4. conio.h provides the 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 a 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 the 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 for what purpose the file needs to be opened or created. 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 (the old file is deleted and a new file is created). In “w” mode, whether 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 the 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 using C Language
#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:
Program For Reading Data From Files using 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 but the first argument must be and the 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 the EOF character then it returns a non-zero value, if it is pointing to other than the 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 characters also. It returns an int value i.e. ASCII value of a character.

Syntax: int getc(FILE* stream);

Program for Reading a line from a file and displaying it using C Language
#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
Program for Reading a line from a file and displaying it using C Language
Example to understand File Handling in C Language:
#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
Example to understand File Handling in C Language
1.txt
File Handling in C Language with Examples
Delay in File Handling

It is a predefined function that is declared in dos.h. By using this function, we can suspend the program from execution. The delay() function requires one argument of type unsigned integer i.e. milliseconds value. By using delay(), we can suspend the program for a minimum of 1 sec and a maximum 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 the end of the 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 the 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 using C Language
#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
Program to Reverse the string data present in a file using C Language
1.txt
Reverse the string data present in a file
Program to Find and Update (or Replace) a Character in a File using C Language
#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 a File using C Language
2.txt
Find and Update a Character in a File
Program for Encoding and Decoding using C Language

#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
Program for Encoding and Decoding using C Language
2.txt (after Encoding)
Program for Encoding and Decoding using C
2.txt (after Decoding)
Program for Encoding and Decoding
Program for Operations on Audio File using C Language

#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
Program for Operations on Audio File using C Language
Program to combine two or more audio files together using C Language
#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
File Handling in C Language with Examples
Follow Us On