Mastering File Handling in C
TABLE OF CONTENTS
??Introduction
??Why do we need File Handling in C?
??Types of Files in C
??Functions in File Operations
??access modes
??Opening or Creating a File
??Reading From a file
??Writing to a File
??Closing a File
??Implementing in C
??Accessing Data from a file
??More Functions
??Introduction
??So far, the C program operations have been performed on a prompt/terminal that has not been saved anywhere. However, in the software industry, most applications are created to save the data retrieved from the program. One method is to save the retrieved data in a file. That is exactly what we are going to learn.??
??Why do we need File Handling in C?
??When a C program is closed, its output is typically destroyed. Sometimes we need to save the output for objectives such as data analysis, result display, output comparison under different conditions, and so on. The use of file management is exactly what the circumstance requires.
??Reusability: The file-handling mechanism records the data generated once the application has been run.
??Data Migration: Files can be transferred from one computer system to another without losing any data. This feature reduces the possibility of incorrect coding.
??Efficient: Some programs may necessitate a huge volume of input. File handling allows you to quickly access a section of code by using individual commands, which saves time and lowers the possibility of errors.
??Storage Capacity: Files allow you to save data without having to worry about storing everything in software simultaneously.
??Types of Files in C
??Generally, a text file contains alphabets, digits, and special characters or symbols, while a binary file contains bytes or a compiled version of the text. It is important to recognize two types of files when dealing with files:
??Text Files:?Text files contain data in the form of ASCII characters and are generally used to store a stream of characters. Each line in a text file ends with a new line character (‘/n’). Text files are used to store the source code.
??Binary Files:?Binary files contain data that is stored similarly to how it is stored in the main memory. Instead of ASCII characters, it is stored in binary format. The binary files can be created only from within a program and their contents can only be read by a program.
??Functions in File Operations
??access modes
?r: Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
?rb: Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
?w: 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: Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
?a: Searches 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. If the file doesn’t exist, a new file is created. 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.
?a+: Searches 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. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
?ab+: Open for both reading and appending in binary mode. If the file does not exist, it will be created.
?Now, if you want to perform operations on a binary file, then you have to append ‘b’ at the last.
领英推荐
??Opening or Creating a File
For performing the operations on the file, a special pointer called File pointer is used which is declared as:
FILE *filePointer;
filePointer = fopen(“demo.txt”, “w”)
??Reading From a file
Can be performed using functions fscanf or fgets.
FILE *filePointer ;
filePointer = fopen(“demo.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", str1, str2, str3, &num);
??Writing to a File
Can be performed by the functions fprintf and fputs with similarities to read operations.
FILE *filePointer ;
filePointer = fopen(“demo.txt”, “w”);
fprintf(filePointer, "%s %s %s %d", "a", "b", "b", 1);
??Closing a File
After every successful file operation, you must always close a file. For closing a file, you have to use fclose() function.
fclose(filePointer)
??Implementing in C
Let's implement whatever we learnt, in C.
1)Program to Open a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>
void main() {
FILE *filePointer; // File Pointer
char text[100] = "Hello, We are learning file Handling"; // input text
//Opening Exixting File in write mode
filePointer = fopen("demo.c", "w");
// If this filePointer is Null
if (filePointer == NULL) {
printf("demo.c failed to open.");
} else {
printf("File opened!\n");
//Write the text in the file
if (strlen(text) > 0) {
// Writing in file
fputs(text, filePointer);
fputs("\n", filePointer);
}
// Closing the file
fclose(filePointer);
printf("Data written\n");
printf("file closed.");
}
}
Output:
file opened!
Data written
file closed.
This program will create a file named demo.c in the same directory, which will contain our text.
2)Program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
void main () {
FILE *filePointer; //file Pointer
char txt[100];
//Opening Exixting File in write mode
filePointer = fopen("demo.c", "r");
// If this filePointer is Null
if (filePointer == NULL) {
printf("demo.c failed to open.");
} else {
printf("File Opened!\n");
while(fgets(txt, 100, filePointer) != NULL) {
printf("%s", txt);
}
fclose(filePointer); // Closing the file
printf("File Closed!");
}
}
Output:
File Opened!
Hello, We are learning file Handling
File Closed!
??Accessing Data from a file
If we have several records in a file and need to access a certain record at a specified point, we must loop through all the records before it to get the record. This wastes a lot of memory and operational time. We can utilise fseek() to reduce memory consumption and operational time by getting to the relevant data more quickly. In C, the fseek() function moves the cursor to the specified record in the file.
Syntax for fseek():
?int fseek(FILE *ptr, long int offset, int pos);
??More Functions
In C, there are several standard library functions for file operations. Some common ones include:
There are several other functions that can be used for other purposes such as fgetc() and fputc() for reading and writing a single character.
Thank You Soo Much for your valuable time.??????
?Mithin Dev
I would love to connect and collaborate.
??GitHub:?github.com/mithindev
??Twitter:?twitter.com/MithinDev
??LinkedIn:?linkedin.com/in/mithin-dev-a-397983247