Basics Of File Handling In C

Basics Of File Handling In C

File handing in C is the process where we can create, open, read, write, and close operations on a file. C language also has different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.

Why do we need File Handling in C?

The essence of why file handling is crucial in programming, especially in the software industry.

File Handling Importance:

  1. Reusability:
  • Data stored in files can be accessed, updated, and deleted, offering high reusability.

2. Portability:

  • Files can be transferred within a computer system without losing data, minimizing the risk of flawed coding.

3. Efficiency

  • File handling allows efficient access to specific parts of a file, saving time and reducing the chance of errors, especially with large datasets.

4. Storage Capacity:

  • Files enable the storage of large amounts of data without the need to manage everything simultaneously within a program.

In summary, file handling enhances the flexibility, portability, efficiency, and storage capacity of programs, making it a fundamental aspect of software development in handling and managing data.

Types of Files in C

A file is divided into two types depending on the way the file can store data. Those two types are:

  • Text Files
  • Binary File

1.Text Files

An overview of text files and their characteristics. Here’s a concise summary:

Text File Characteristics:

a. Data Format:

  • Contains data in the form of ASCII characters.

b. Line Termination:

  • Each line ends with a new line character ('\n').

c.Readability:

  • Readable and writable by any text editor.

d. File Extension:

  • Typically stored with a .txt file extension.

e. Versatility:

  • Commonly used to store a stream of characters.

f. Source Code Storage:

  • Can be utilized to store source code.

In essence, text files are versatile and widely compatible for storing and accessing human-readable data, making them a standard choice for various applications, including storing source code.

2. Binary Files

Binary File Characteristics:

a .Data Format:

  • Contains data in binary form (0’s and 1’s), mirroring the storage in main memory.

b. Creation Source:

  • Created programmatically from within a program.

c. Readability

  • Contents can only be read by a program, not easily readable by humans.

d. Security:

  • More secure due to the non-human-readable nature of binary data.

e. File Extension:

  • Generally stored with a .bin file extension.

Binary files are preferred for their efficient representation of data in a manner similar to main memory storage, and their increased security due to the non-human-readable format. They are commonly used for storing data that is meant to be processed by programs rather than viewed directly by users.

C File Operations

C File Operations:

a. Creating a New File:

  • Use fopen() with attributes like “a”, “a+”, “w”, or “w+” to create a new file.

b.Opening an Existing File

  • Use fopen() to open an existing file.

c. Reading from File:

  • Use fscanf() or fgets() to read data from a file.

d.Writing to a File:

  • Use fprintf() or fputs() to write data to a file.

e. Moving to a Specific Location in a File:

  • Use fseek(), rewind() to navigate to a specific position in a file.
  • f.Closing a File:

f.Closing a File:

  • Use fclose() to close the file after operations are completed.

These operations collectively allow manipulation, reading, and writing of data to and from files in the C programming language, providing flexibility in handling data persistence.

Functions for C File Operations

File Pointer in C

In C programming, a file pointer is like a marker that points to a specific spot in an open file. This pointer is essential for carrying out file operations such as reading, writing, and closing. To declare a file pointer variable, we use the FILE macro, which is defined in the header file. The file pointer essentially helps us keep track of where we are in a file, enabling us to perform different operations effectively.

Syntax of File Pointer

FILE* pointer_name;

Open a File in C

For opening a file in C, the fopen() works with the filename or file path along with the required access modes.

Syntax of fopen()

FILE* fopen(const char *file_name, const char *access_mode);

Parameters

The term “file_name” refers to the name of a file. If the file is in the same directory as the source file, you only need to provide its name. Otherwise, if the file is located in a different directory, you should include the full path to the file.

The “access_mode” is a specification indicating the purpose for which the file is being opened. It signifies the type of operation you want to perform on the file, whether it’s for reading, writing, or both.

Return Value

  1. If the file is successfully opened, the program receives a file pointer, which is like a reference allowing it to interact with the contents of the file.
  2. If the attempt to open the file fails for some reason, the program gets a special value called NULL. This indicates that the file wasn’t opened, and the program needs to handle this situation accordingly

File opening modes in C

File opening modes or access modes which would grand allowed operations on the file to be opened. Hence,they are passed as an argument to the fopen() function. Commonly used file access modes are listed below:

Opening ModesDescription
rIt function to Searches file. If the file is opened successfully fopen( ) loads it into memory and would sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ), then it will returns NULL.
rb This refers to Open the reading in binary mode. If the file does not exist, then fopen( ) returns NULL.
wThis refers to Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
wbThis refers to Open for writing in binary mode. If the file exists and their contents are overwritten. If the file does not exist, it will be created.
aThis indicates to Searche file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that would points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file would be made. Returns NULL, if unable to open the file.
ab Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.
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. Returns NULL, if unable to open the file.
rb+ This will Open for both reading and writing in binary mode. If the file does not exist, fopen( ) will returns NULL.
w+This indicate Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open the file.
wb+This will Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be formed.
a+This refers to Searching 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. It opens the file in both reading and append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
ab+It will Open for both reading and appending in binary mode. If the file does not exist, it will be created.

According to the file access mode given above , if you want to do operations on a binary file, then you have to append ‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use “a+b”.

Example of Opening a File

// C Program to illustrate file opening
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    // file pointer variable to store the value returned by
    // fopen
    FILE* fptr;
 
    // opening the file in read mode
    fptr = fopen("filename.txt", "r");
 
    // checking if the file is opened successfully
    if (fptr == NULL) {
        printf("The file is not opened. The program will "
               "now exit.");
        exit(0);
    }
 
    return 0;
}

Output

The file is not opened. The program will now exit.

Create a File in C

The fopen() function not only opens existing files but can also create a new file if it doesn’t already exist. To achieve this, you use specific modes that allow file creation. These modes include “w,” “w+,” “wb,” “wb+,” “a,” “a+,” “ab,” and “ab+.” When you use one of these modes, the function opens the file for writing, and if the file doesn’t exist, a new one is created. This flexibility is useful when you want to handle both existing and new files in your program.

FILE *fptr;
fptr = fopen("filename.txt", "w");

Example



// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    // file pointer
    FILE* fptr;
 
    // creating file using fopen() access mode "w"
    fptr = fopen("file.txt", "w");
 
    // checking if the file is created
    if (fptr == NULL) {
        printf("The file is not opened. The program will "
               "exit now");
        exit(0);
    }
    else {
        printf("The file is created Successfully.");
    }
   
    return 0;
}

Output

The file is created Successfully.

Reading From a File

In C, reading from a file is done using functions like fscanf() or fgets(). These functions perform similar operations to scanf() and gets(), but they have an additional parameter – the file pointer. This file pointer helps specify the file from which data should be read.

fscanf()It will Use formatted string and variable arguments list to take input from a file. 
fgets()It has Input the whole line from the file.
fgetc()It will Read a single character from the file.
fgetw()It will Read a number from a file.
fread()It will Read the specified bytes of data from a binary file.

Example

FILE * fptr; 
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);

Write to a File

In C programming, writing to a file is accomplished using functions like fprintf() and fputs(), which are similar to the read operations but are used for writing data. These functions, like their read counterparts, also require a file pointer as an additional parameter to specify the target file.

FunctionDescription
fprintf()It works Similar to printf(), this function use formatted string and varible arguments list to print output to the file.
fputs()It will Prints the whole line in the file and a newline at the end.
fputc()It will Prints a single character into the file.
fputw()It will Prints a number to the file.
fwrite()This functions write the specified amount of bytes to the binary file.

Example

FILE *fptr ; 
fptr = fopen(“fileName.txt”, “w”);fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);fputc("a", fptr);

Closing a File

The fclose() function is basically used to close the file. After successful file operations, you must always close a file to remove it from the memory.

Syntax of fclose()

fclose(file_pointer);

File_pointer is used to open the file

Example

FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);

Examples of File Handing in C

Example 1: Program to Create a File, Write in it, And Close the File

// C program to Open a File,
// Write in it, And Close the File
#include <stdio.h>
#include <string.h>
 
int main()
{
 
    // Declare the file pointer
    FILE* filePointer;
 
    // Get the data to be written in file
    char dataToBeWritten[50] = "Skillvertex-A Computer "
                               "Science Portal for Skill";
 
    // Open the existing file GfgTest.c using fopen()
    // in write mode using "w" attribute
    filePointer = fopen("GfgTest.c", "w");
 
    // Check if this filePointer is null
    // which maybe if the file does not exist
    if (filePointer == NULL) {
        printf("GfgTest.c file failed to open.");
    }
    else {
 
        printf("The file is now opened.\n");
  // Write the dataToBeWritten into the file
        if (strlen(dataToBeWritten) > 0) {
 
            // writing in the file using fputs()
            fputs(dataToBeWritten, filePointer);
            fputs("\n", filePointer);
        }
 
        // Closing the file using fclose()
        fclose(filePointer);
 
        printf("Data successfully written in file "
               "GfgTest.c\n");
        printf("The file is now closed.");
    }
   
    return 0;
}

Output

The file is now opened.
Data successfully written in file GfgTest.c
The file is now closed.

Example 2: Program to Open a File, Read from it, And Close the File

// C program to Open a File,
// Read from it, And Close the File
#include <stdio.h>
#include <string.h>
 
int main()
{
 
    // Declare the file pointer
    FILE* filePointer;
 
    // Declare the variable for the data to be read from
    // file
    char dataToBeRead[50];
 
    // Open the existing file GfgTest.c using fopen()
    // in read mode using "r" attribute
    filePointer = fopen("GfgTest.c", "r");
 
    // Check if this filePointer is null
    // which maybe if the file does not exist
    if (filePointer == NULL) {
        printf("GfgTest.c file failed to open.");
    }
    else {
 
        printf("The file is now opened.\n");
 
        // Read the dataToBeRead from the file
        // using fgets() method
        while (fgets(dataToBeRead, 50, filePointer)
               != NULL) {
 
            // Print the dataToBeRead
            printf("%s", dataToBeRead);
        }
 
        // Closing the file using fclose()
        fclose(filePointer);
 
        printf(
            "Data successfully read from file GfgTest.c\n");
        printf("The file is now closed.");
    }
    return 0;
}

Output

The file is now opened.
Skillvertex-A Computer Science Portal for Skill
Data successfully read from file GfgTest.c
The file is now closed.

Read and Write in a Binary File

Opening a Binary File

This will help to open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the fopen() function. It will also use the .bin file extension in the binary filename.

Example

fptr = fopen("filename.bin", "rb");

Write to a Binary File

We use the fwrite() function to write data to a binary file. The data will be written to the binary file in the from of bits (0’s and 1’s).

Syntax of fwrite()

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);

Parameters:

  • ptr: This is a pointer to the block of memory containing the data you want to write.
  • size: Specifies the size of each element to be written, measured in bytes.
  • nmemb: Represents the number of elements you want to write to the file.
  • file_pointer: This is the FILE pointer that points to the output file stream. It indicates the file where the data should be written.

Rerurn Value

Number of objects written.

Example

// C program to write to a Binary file using fwrite()
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
    int n1, n2, n3;
};
int main()
{
    int n;
    // Structure variable declared here.
    struct threeNum num;
    FILE* fptr;
    if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) {
        printf("Error! opening file");
        // If file pointer will return NULL
        // Program will exit.
        exit(1);
    }
    int flag = 0;
    // else it will return a pointer to the file.
    for (n = 1; n < 5; ++n) {
        num.n1 = n;
        num.n2 = 5 * n;
        num.n3 = 5 * n + 1;
        flag = fwrite((&num, sizeof(struct threeNum), 1,
                      fptr);
    }
 
    // checking if the data is written
    if (!flag) {
        printf("Write Operation Failure");
    }
    else {
        printf("Write Operation Successful");
    }
 
    fclose(fptr);
   
    return 0;
}

Output

Write Operation Successful

Reading from Binary File

The fread() function is used to read data from a binary file in C. The data is read from the file in the same form as it will be stored i.e. binary form.

Syntax

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);

Parameters

  • ptr: This is a pointer to the block of memory where the read data will be stored.
  • size: Specifies the size of each element to be read, measured in bytes.
  • nmemb: Represents the number of elements you want to read from the file.
  • file_pointer: This is the FILE pointer that points to the input file stream. It indicates the file from which data should be read.

Return Value

Number of Objects that will be written

Example

// C Program to Read from a binary file using fread()
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
    int n1, n2, n3;
};
int main()
{
    int n;
    struct threeNum num;
    FILE* fptr;
    if ((fptr = fopen("C:\\program.bin", "rb")) == NULL) {
        printf("Error! opening file");
        // If file pointer will return NULL
        // Program will exit.
        exit(1);
    }
    // else it will return a pointer to the file.
    for (n = 1; n < 5; ++n) {
        fread(&num, sizeof(struct threeNum), 1, fptr);
        printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,
               num.n3);
    }
    fclose(fptr);
 
    return 0;
}

Output

n1: 1   n2: 5   n3: 6
n1: 2   n2: 10  n3: 11
n1: 3   n2: 15  n3: 16
n1: 4   n2: 20  n3: 21

fseek() in C

When dealing with a file containing multiple records, finding a specific record by looping through all the preceding ones can be inefficient in terms of both memory and time. To address this, we use the fseek() function in C, which efficiently moves the file cursor to a specified record.

With fseek(), we can directly navigate to the desired record in the file, reducing the need to iterate through all preceding records. This not only saves memory but also speeds up the operation, making it a more efficient way to access specific data within a file

Syntax

int fseek(FILE *ptr, long int offset, int pos);

Example



// C Program  to demonstrate the use of fseek() in C
#include <stdio.h>
 
int main()
{
    FILE* fp;
    fp = fopen("test.txt", "r");
 
    // Moving pointer to end
    fseek(fp, 0, SEEK_END);
 
    // Printing position of pointer
    printf("%ld", ftell(fp));
 
    return 0;
}

Output

81

Rewind() in C

The rewind() function in C is used to reset the file pointer, bringing it back to the beginning of the file. This function is convenient when you specifically want the file pointer to be positioned at the start of the file. It serves as an alternative to using fseek() for this purpose.

Symtax

rewind (file_pointer);

Example

// C program to illustrate the use of rewind
#include <stdio.h>
 
int main()
{
    FILE* fptr;
    fptr = fopen("file.txt", "w+");
    fprintf(fptr, "Skillvertex \n");
 
    // using rewind()
    rewind(fptr);
 
    // reading from file
    char buf[50];
    fscanf(fptr, "%[^\n]s", buf);
 
    printf("%s", buf);
 
    return 0;
}

Output

Skillvertex

More Functions for C File Operations

FunctionsDescription
fopen()This function willl create a file or to open a file.
fclose() fclose() will close a file.
fgets()This function will read a file.
fprintf()This function will write blocks of data into a file.
fscanf()fscanf() willread blocks of data from a file.
getc()This function will read a single character to a file.
putc()This function will write a single character to a file.
fseek()This function will set the position of a file pointer to a mentioned location.
ftell() ftell() will return the current position of a file pointer.
rewind()rewind() will set the file pointer to the beginning of a file.
putw()It is used to write an integer to a file.
getw()This function will read an integer from a file.

FAQ- Basics of File Handling in C

Q1.What is the basic of file handling in C?

Ans. In C programming, file handling is about how a program saves its data into a file. It’s like storing information in a place that can be easily accessed later. This stored data can be used again in different parts of the program whenever needed.

Q2. How to use files in C?

Ans. Create a variable: Make a variable of type “FILE*”.
Open the file: Use the “fopen” function to open the file and assign it to the variable.
Check if successful: Verify if the file was opened successfully by checking if the variable is equal to NULL.

Q3. How to write file in C?

Ans. Creating a new file: Use fopen() with attributes like “a”, “a+”, “w”, or “w+”.
Opening an existing file: Simply use fopen().
Reading from a file: Use fscanf() or fgets().
Writing to a file: Use fprintf() or fputs().
Moving to a specific location in a file: Utilize fseek() or rewind().
Closing a file: Employ fclose().

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment