File Handling in C

File Handling in C

5 mins read440 Views Comment
clickHere
Updated on Feb 9, 2023 16:48 IST

This article deals with File Handling in C and will answer your query regarding is its usage.This concept is cleared with programming example in C.

2023_01_MicrosoftTeams-image-26.jpg

Introduction

In programming, we might need a specific type of input data to be created multiple times. Sometimes more than just displaying some facts over the console is required. The quantity of data that can be displayed on the console may be extremely small or very vast. Because the memory is volatile, repeatedly restoring the programmatically generated data is hard. However, the user can store data on the local system, as it is accessible whenever he needs to. Here, file handling in C becomes necessary.

Table of contents

File Handling in C

Data storage in a file using a program is known as file handling. Programs are written in C using file handling for storing the results and other program data in files. To use the data in the application, we may also extract or fetch it from a file.

We can use our C application to update, create, read, and delete files that are stored on the local file system thanks to file handling in C. A file can undergo the following procedures:

  • Creation of a new file
  • Opening an existing file
  • Reading from the file
  • Writing to the file
  • Deleting the file

Why file handling in C

There are occasions when a program’s output, after it has been compiled and run, does not meet our objectives. In these circumstances, the user would want to verify the program’s output several times. It takes a lot of work for any programmer to compile and run the same program repeatedly. This is the precise situation where file handling is helpful.

  • Reusability: The process of File handling helps the user by allowing him to preserve all the information or the data that is generated after he runs the designed program.
  • Saves Time: In some cases, the programs need a large amount of user input. Here, file handling allows the user to access part of the code using individual commands easily.
  • Commendable storing capacity: While storing data in the files, the user can leave behind the stress of storing information in bulk in the program.
  • Portability: The availability of contents in any file is easily transferable to another without any hassle and data loss in the system. Hence, saving a lot of time and effort along with minimizing the risk of flawed coding.
Factorial Programs in C – A Step-by-Step Guide
Factorial Programs in C – A Step-by-Step Guide
In this article, we will discuss how to calculate the factorial programming in c using three different methods: For Loops, Recursion, and While Loop.
Difference between Malloc and Calloc
Difference between Malloc and Calloc
Malloc and Calloc are dynamic memory allocation methods in C language. You will learn the differences between these two. And will also see the applications of them. In this article...read more
If Else Statement in C Programming: Syntax and Examples
If Else Statement in C Programming: Syntax and Examples
Have you heard of the if-else statement in the c programming language? Let us understand this concept in detail and understand it using examples! Through this article, you will know...read more

Also explore: Top 80+ C Programming Interview Questions and Answers

File Handling Function in C

A file can be easily opened, expanded upon, read, created, deleted, closed, searched for, etc., via some different functions. 

In C, we can refer to these as file-handling operators.

fopen()

Opens a file

fprint()

Prints an available file

fscan()

Reads the data present in the file

fputc()

Writes a character to the file

fgetc()

Reads the character to the file

fseek()

Sets the pointer to the intended file position 

fclose()

Closes a program file

fputw()

Writes an integer from the file

fgetw()

Reads an integer from the file

ftell()

Tells the current position of the file

We use a straightforward text editor to create the text files with the.txt extension. The binary files contain the data and information using the 1s and 0s binary coding scheme. The disadvantage of text files in a program is fixed by creating binary files, which have the extension.bin.

fopen()

Before a file may be read, written to, or updated, the user must open it. A file is opened using the fopen() method. Below is the syntax for fopen() function.

File = fopen(“Name_of_file”,”mode)

There are a few file-opening modes present in the C language. Let us have a look at them below:

r

Will open a text file (read mode only)

w

Will open a text file (write mode only)

a

Will open a text file (append mode only)

r+

Will open a text file (both read and write modes)

w+

Will open a text file (both read and write modes)

rb

Will open a binary file (read mode only) 

wb

Will open a binary file (write mode only)

ab

Will open a binary file (append mode only)

rb+

Will open a binary file (both read and write modes)

wb+

Will open a binary file (both read and write modes)

ab+

Will open a binary file (both read and write modes)

fClose() – Closing a file 

Once a program has finished writing or reading a file, it must be closed (for both text and binary files). The fclose() method in a program is used to close a file.

The program seems to be like this:

 
fclose(fptr);
Copy code

The file pointer needed to close this file in a program is referred to as the fptr in this situation.

fscan(), fprint() : Reading the data into file 

The two functions fscanf() and fprintf() functions are used to write and read data into the text file, respectively. These are the file equivalents of the scanf() and printf() functions. However, there is a significant distinction: fscanf() and fprintf() require a reference pointing to the program’s structure FILE.

Let us see the program below and see how file handling works in C:

C program to Open a File

 
// C program to Open a File,
// Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *file ;
char dataToBeWritten[50]
= "NaukriInfo - Giving best experience to its learners";
file = fopen("ABC.c", "w") ;
if ( file == NULL )
{
printf( "The ABC.c file failed to open." ) ;
}
else
{
printf("The file is open\n") ;
if ( strlen ( dataToBeWritten ) > 0 )
{
fputs(dataToBeWritten, file) ;
fputs("\n", file) ;
}
fclose(file) ;
printf("The data is successfully written");
printf("The file is close") ;
}
return 0;
}
Copy code

The output of the program will be:

The ABC.c file failed to open.

In this program, we have created a file pointer as a file, and the data is then fetched to be written into the file. Then we open the existing file ABC.c using fopen() in the write mode using the ‘w’ attribute. We will check if the file is empty by using file ==NULL, which may also mean that the file is not existing. We will insert the data into the file using fputs() function, and in the end, we will close the file using fclose() function. 

Conclusion

In this article, we have talked about file handling using the C language. Data storage in a file using a program is known as file handling. To use the data in the application, we may also extract or fetch it from a file.

We can use file handling in C to update, create, read, and delete files stored on the local system. File handling can undergo the creation of a file, opening, reading, and writing as well as closing a file. We have discussed the need for file handling in C and a demonstration of how to execute the functions in C using file handling. 

Contributed by-Megha Chadha

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio