File Handling in C Programming - IndianTechnoEra
Latest update Android YouTube

File Handling in C Programming

 

Introduction:

In addition to standard, I/O, C programming also provides file I/O functions for reading and writing data to and from files. 

File I/O (Input/Output) is an important concept in any programming language, including C. 

In C programming, file I/O operations are used to read data from and write data to files. 

1. File Handling:

File handling is an essential aspect of programming in C. 

It enables you to read from and write to files, which is crucial for tasks such as data storage, retrieval, and manipulation. 

In this comprehensive guide, we will delve into the world of file handling in C programming, covering the following topics:

  • Introduction to File Handling
  • Opening and Closing Files
  • Reading from Files
  • Writing to Files
  • File Pointers
  • Binary Files vs. Text Files
  • Error Handling
  • Example Programs

Reading from Files: To read data from a file, you can use functions like fgetc(), fgets(), or fread(). For example, fgetc() reads one character at a time, while fgets() reads a line of text.

Writing to Files: To write data to a file, you can use functions like fputc(), fputs(), or fwrite(). For example, fputc() writes one character at a time, while fputs() writes a string.

File Pointers: File pointers are crucial when reading from or writing to files. They keep track of the current position in the file. You can use functions like fseek() to move the file pointer to a specific position.

2. File I/O functions:

File I/O functions are defined in the stdio.h header file and include the following:

  • - fopen(): used to open a file
  • - fclose(): used to close a file
  • - fgetc(): used to read a single character from a file
  • - fgets(): used to read a line of text from a file
  • - fprintf(): used to write formatted output to a file
  • - fscanf(): used to read formatted input from a file

2.1 fopen(): Open a file

The fopen() function is used to open a file. 

It takes two arguments: the name of the file and the mode in which the file is to be opened. 

Here's how to open a file in various modes:

  • "r": Read (file must exist)
  • "w": Write (creates a new file or overwrites an existing file)
  • "a": Append (creates a new file or appends to an existing file)

For example, to open a file named "data.txt" in read mode, we can use the following code:

FILE *fp;

fp = fopen("data.txt", "r");

Here, the function returns a pointer to a FILE object, which is used to access the file.

2.2 fclose(): Close a file:

The fclose() function is used to close a file. 

It takes one argument: the file pointer returned by the fopen() function. 

For example, to close the file opened in the previous example, we can use the following code:

fclose(fp);

2.3 fscanf(): Read file data

The fscanf() function is used to read data from a file. 

It takes the file pointer, the format string, and the address of the variables where the data will be stored. 

For example, to read an integer value from a file, we can use the following code:

int num;

fscanf(fp, "%d", &num);

2.4 fprintf(): Write data file

The fprintf() function is used to write data to a file. 

It takes the file pointer, the format string, and the data to be written. 

For example, to write an integer value to a file, we can use the following code:

int num = 10;

fprintf(fp, "The value of num is %d\n", num);

2.5 fgetc() & fputc(): R, W single character

The fgetc() function is used to read a single character from a file, while the fputc() function is used to write a single character to a file. 

They take the file pointer as an argument. 

For example, to read a character from a file, we can use the following code:

char ch;

ch = fgetc(fp);


And to write a character to a file, we can use the following code:

char ch = 'a';

fputc(ch, fp);

2.6 fgets() & fputs(): R, W single string

The fgets() function is used to read a string of characters from a file, while the fputs() function is used to write a string of characters to a file. 

They take the file pointer and the maximum number of characters to be read/written as arguments. 

For example, to read a string of characters from a file, we can use the following code:

char buffer[100];

fgets(buffer, 100, fp);


And to write a string of characters to a file, we can use the following code:

char buffer[100] = "Hello, World!";

fputs(buffer, fp);


3. Binary Files vs. Text Files

It's important to understand the difference between binary and text files. Binary files store data in a non-human-readable format, while text files store data in plain text. You should choose the appropriate file type based on your data and requirements.

3.1 Binary Files

Binary files are files that store data in a format that is not human-readable. They contain raw binary data, which can represent any type of information, such as images, audio, video, or even complex data structures. Binary files preserve the exact bit pattern of the data they store.

3.2 Here are some characteristics of binary files:

Data Preservation: Binary files preserve the exact bit pattern of the data they contain. This means that if you read and write data to a binary file, the data's integrity remains intact.

Non-Text Data: Binary files are suitable for storing non-textual data, including multimedia files, executable programs, and complex data structures like databases.

No Character Encoding: Unlike text files, binary files do not use character encoding schemes like ASCII or UTF-8. They do not interpret data as characters but as raw binary values.

Use Cases: Binary files are commonly used for tasks where preserving data integrity is crucial, such as multimedia applications, database storage, and data interchange between different systems.


3.3 Text Files

Text files, on the other hand, are files that store data in a human-readable format. They contain text characters encoded using character encoding schemes like ASCII, UTF-8, or others. Text files are primarily used for storing textual information, such as documents, configuration files, or source code.

3.4 Here are some characteristics of text files:

Human-Readable: Text files contain data that can be easily read and edited by humans. Each character is represented using a character encoding, making the content understandable.

Line-Based: Text files are often organized into lines of text, with each line ending with a newline character ('\n' in many systems). This line-based structure is suitable for structured textual data.

Character Encoding: Text files use character encoding schemes to represent characters, allowing support for different languages and characters beyond the ASCII character set.

Use Cases: Text files are widely used for storing textual information, including plain text documents, source code files, configuration files, and log files.

3.5 Choosing Between Binary and Text Files

When deciding whether to use binary or text files, consider the nature of your data and your specific requirements:

Use binary files when you need to store non-textual data or when data integrity is critical.

Use text files when dealing with human-readable text data, such as documents, configuration files, or source code.

Understanding the distinction between these file types is essential for effective file handling in C programming, as it influences how you read from and write to files based on their content and format.

4. Example Programs

To illustrate file handling in C, here are two example programs:

4.1 Reading from a Text File

#include <stdio.h>
int main() {
    FILE *file;
    char ch;
    // Open the file for reading
    file = fopen("sample.txt", "r");
    // Check if the file exists
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    // Read and print the file content character by character
    while ((ch = fgetc(file)) != EOF) {
        printf("%c", ch);
    }
    // Close the file
    fclose(file);
    return 0;
}


4.2 Writing to a Text File

#include <stdio.h>
int main() {
    FILE *file;
    char text[] = "Hello, File Handling!";
    // Open the file for writing (creates if not exists)
    file = fopen("output.txt", "w");
    // Check if the file was opened successfully
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
    // Write the text to the file
    fputs(text, file);
    // Close the file
    fclose(file);
    return 0;
}


 Key:  File I/O, fopen(), fclose(), fscanf(), fprintf(), fgetc(), fputc(), fgets(), fputs(), Error Handling, try and catch.

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.