File Handling in C
File handling in C involves a series of operations including creation, opening, reading, writing, and closing of files. To accomplish these tasks, C provides a set of functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), among others. These functions enable input, output, and various file operations in C programs.
Why do we need File Handling in C?
File handling in C is crucial for various reasons, enhancing the functionality and usability of programs:
- Reusability: Data stored in files can be accessed, modified, and deleted as needed, providing high reusability of information.
- Portability: Files can be easily transferred between different systems without data loss. This feature minimizes the risk of coding errors and ensures seamless operation across platforms.
- Efficiency: File handling in C simplifies the process of accessing and manipulating large amounts of data. It allows programs to efficiently retrieve specific information from files with minimal code, saving time and reducing the likelihood of errors.
- Storage Capacity: Files provide a means to store vast amounts of data without the need to hold everything in memory simultaneously. This capability is particularly useful for handling large datasets and prevents memory overload in programs.
Types of Files in C
We will be working with two types of files: -
- Text file
- Binary file
Let’s understand them in brief -
Text file - The user can create these files easily while handling files in C. It stores information in the form of ASCII characters internally, and when the file is opened, the content is readable by humans. It can be created by any text editor with a .txt or .rtf (rich text)extension. Since text files are simple, they can be edited by any text editor like Microsoft Word, Notepad, Apple Text Edit, etc.
Binary file - It stores information in the form of 0’s or 1’s, and it is saved with the .bin extension, taking less space. Since it is stored in a binary number system format, it is not readable by humans. Therefore it is more secure than a text file.
C File Operations
There are different kinds of file operations in C:
- Creating a new file
- Opening an existing file
- Reading from file
- Writing to a file
- Moving to a specific location in a file
- Closing a file
Functions for C File Operations
File Operation | Declaration & Description Reframed in Points |
---|---|
fopen() - To open a file | - FILE *fopen(const char *filename, const char *mode) opens or creates a file. - Declares a file pointer FILE *fp for file operations. - filename: Name/path of the file. - mode: Defines file access mode (e.g., read r, write w, append a). - Creates a new file if it doesn't exist. |
fclose() - To close a file | - int fclose(FILE *fp) terminates the file pointer. - Closes the file associated with fp. - Should be called to properly end file operations. |
fgets() - To read a file | - char *fgets(char *string, int n, FILE *fp) reads lines from a file. - string: Buffer to store the data. - n: Maximum number of characters to read (including the null terminator). - fp: File pointer to the file being read. |
fprintf() - To write into a file | - int fprintf(FILE *fp, const char *format, ...) writes a string to a file. - Sends formatted output to a file pointed to by fp. - format: The string provided for writing may include embedded format specifiers, allowing for dynamic content insertion during the writing process. |
File Pointer in C
In file handling in C, a file pointer serves as a reference to a specific position within an opened file. It facilitates various file operations in C like reading, writing, closing, and more. The FILE macro is employed to declare a file pointer variable, and it is defined within the <stdio.h> header file.
Syntax of File Pointer
File pointers are utilized extensively in nearly all file operations in C programming.
Open a File in C
To open a file in C, the fopen() function is employed, specifying the filename or file path along with the desired access modes.
Syntax of fopen()
Parameters
- file_name: If the file resides in the same directory as the source file, provide its name; otherwise, specify the full path.
- access_mode: Specifies the operation for which the file is being opened.
Return Value
- If the file is successfully opened, it returns a file pointer to it.
- If the file fails to open, it returns NULL.
File opening modes in C
We use fopen() with different opening modes to open a file. The most common modes used are listed below.
Mode | Description | Example |
---|---|---|
r | Opens a text file in read-only mode, allowing only reading operations. | Example: fopen("demo.txt", "r") |
w | When using the mode "w", fopen() initializes a text file for writing exclusively. If the file already exists, it clears its contents; otherwise, it creates a new file for writing. | Example: fopen("demo.txt", "w") |
a | When employing the "a" mode, fopen() enables opening a text file in append mode. This mode permits writing data to the end of the file, preserving existing content. | Example: fopen("demo.txt", "a") |
r+ | When using the "r+" mode, fopen() facilitates opening a text file for both reading and writing operations. This mode grants the ability to manipulate data at any position within the file. | Example: fopen("demo.txt", "r+") |
w+ | This mode opens a text file for both reading and writing. If the file with same name already exists, it truncates the file to zero length; otherwise, it creates a new file for both reading and writing operations. | Example: fopen("demo.txt", "w+") |
a+ | This mode opens a text file for both reading and writing, enabling data to be appended to the end of the file without overwriting existing content. | Example: fopen("demo.txt", "a+") |
rb | Opens a binary file in read-only mode, allowing reading operations on binary data. | Example: fopen("demo.txt", "rb") |
wb | Opens a binary file in write-only mode, truncating the file to zero length if it exists or creating a new file for writing binary data. | Example: fopen("demo.txt", "wb") |
ab | Opens a binary file in append mode, allowing binary data to be written to the end of the file without overwriting existing content. | Example: fopen("demo.txt", "ab") |
rb+ | Opens a binary file for both reading and writing operations on binary data. | Example: fopen("demo.txt", "rb+") |
wb+ | Opens a binary file for both reading and writing operations, truncating the file to zero length if it exists or creating a new file for reading and writing binary data. | Example: fopen("demo.txt", "wb+") |
ab+ | This mode opens a binary file for both reading and writing operations, allowing binary data to be appended to the end of the file without overwriting existing content. | Example: fopen("demo.txt", "ab+") |
In append mode, we can write data into an existing file without deleting existing contents. In contrast, in write mode, existing data is deleted, which was already present in the file.
Example of Opening a File
Create a File in C
The fopen() function in C not only opens existing files but also creates a new file if it doesn't already exist. This behavior is achieved by using specific modes that allow file creation, such as "w", "w+", "wb", "wb+", "a", "a+", "ab", and "ab+".
Example of Creating a File
Reading From a File
To read data from an existing file, we will use “r” mode in file opening. To read the file character by character, we use getc(). And to read line by line, we use fgets().
Additionally, there exist alternative functions available for reading from a file, which are enumerated below:
Function | Description |
---|---|
fscanf() | Retrieves input from a file using a formatted string and variable argument list. |
fgets() | Obtains a complete line of text from the file. |
fgetc() | Reads a single character from the file. |
fgetw() | Reads a numerical value from the file. |
fread() | Extracts a specified number of bytes from a binary file. |
Example
In the program above, the getc() function is utilized to read the file character by character until it reaches the end of the file (EOF).
As file2.txt was already present in my directory, the output is as shown.
Output:
Write to a File
File writing operations in C are facilitated by functions like fprintf() and fputs(), which exhibit similarities to their counterparts used for reading operations. Additionally, C programming provides several other functions suitable for writing data to a file, including:
Function | Description |
---|---|
fprintf() | This function, akin to printf(), uses a formatted string and variable arguments list to print output to the file. |
fputs() | Prints an entire line in the file along with a newline character at the end. |
fputc() | Writes a single character into the file. |
fputw() | Writes a number to the file. |
fwrite() | Writes the specified number of bytes to the binary file. |
Example
Output:
Closing a File
The fclose() function is utilized to close a file in C programming. It is essential to close a file after performing file operations in C to release system resources and ensure proper memory management.
Syntax of fclose()
Here, file_pointer is a pointer to the opened file that you want to close.
Example:
After completing the necessary file operations in C, the fclose() function is called to close the file pointed to by fptr.
Examples of File Handling in C
Example 1: Program to Create a File, Write in it, And Close the File
Output:
Example 2: Program to Open a File, Read from it, And Close the File
Output:
Read and Write in a Binary File
Opening a Binary File
When intending to operate on a file in binary mode, utilize the access modes "rb", "rb+", "ab", "ab+", "wb", or "wb+" with the fopen() function. Additionally, employ the ".bin" file extension for binary files.
Example:
In this example, the file "example.bin" is opened in binary mode for reading using the "rb" access mode.
Write to a Binary File
When writing data to a binary file, the fwrite() function proves invaluable. This function allows us to store information in binary form, comprising sequences of bits (0s and 1s).
Syntax of fwrite()
Parameters
- ptr: A reference to the memory block holding the data intended for writing.
- size: The byte size of each element to be written.
- nmemb: The count of elements to be written.
- file_pointer: The FILE pointer associated with the output file stream.
Return Value
The function returns the number of objects successfully written.
Example: Program to write to an Binary file using the fwrite() function
Output:
Reading from Binary File
When retrieving data from a binary file, the fread() function serves as a pivotal tool. This function facilitates the extraction of data from the file in its binary representation.
Syntax of fread()
Parameters
- memory_ptr: A pointer to the memory block where the data will be stored.
- size: The size of each element to be read (in bytes).
- nmemb: The number of elements to be read.
- file_pointer: The FILE pointer pointing to the input file stream.
Return Value
The function returns the number of objects successfully read.
Example: Program to Read from an binary file using the fread() function
Output:
fseek() in C
When dealing with files containing multiple records, locating a specific record can be cumbersome and inefficient if we have to traverse through all the preceding records. This not only consumes memory but also increases operational time. To address this, we can utilize fseek() which efficiently positions the file cursor to the desired record.
Syntax for fseek()
Parameters
- file_ptr: Pointer to the file stream.
- offset: Number of bytes to offset from the position specified by pos.
- pos: Position from where the offset is applied. It can take one of the following values:
- SEEK_SET: Beginning of the file.
- SEEK_CUR: Current position of the file pointer.
- SEEK_END: End of the file.
Example of fseek()
In this instance, we initiate the opening of a binary file named "data.bin" for reading in binary mode ("rb"). We then use fseek() to move the file pointer to the end of the file (SEEK_END). Finally, we print the position of the file pointer using ftell(), which will indicate the size of the file in bytes.
rewind() in C
The rewind() function in C is utilized to move the file pointer back to the beginning of the file. It serves as a convenient alternative to fseek() when the intention is to position the file pointer at the start of the file.
Syntax of rewind()
Example
In this example, we open a file named "data.txt" in write mode with reading capabilities ("w+"). We write the string "Hello, World!\n" to the file using fprintf(). Then, we use rewind() to reset the file pointer to the beginning of the file. Next, we read the content of the file using fscanf(), storing it in the buffer array, and finally, we print the content read from the file.
Output:
More Functions for C File Operations
Function | Description | Syntax |
---|---|---|
fopen() | Used to open an existing file or to create a new file | FILE *fopen(“file_name”, “mode”); |
fprintf() | Used to write data in existing file | fprintf(FILE *stream, const char *format [, argument, ...]) |
fscanf() | Used to read data from the file | fscanf(FILE *stream, const char *format [, argument, ...]) |
fputc() | Used to write characters in a file | fputc(int c, FILE *stream) |
fgetc() | Used to read characters from a file | fgetc(FILE *stream) |
fclose() | Used to close existing file | fclose( FILE *fp ) |
fseek() | puts the file pointer to the specified place | fseek(FILE *stream, long int offset, int whence) |
fputw() | Used to write integral value in the file | fputw(int number,File *fp) |
fgetw() | Used to read integral value from the file | fgetw(File *fp) |
ftell() | It will return the current position of the file pointer in the file | ftell(FILE *stream) |
rewind() | the file pointer is set to the start of the file | rewind(FILE *stream) |
Conclusion
- File handling in C is essential for various operations such as creation, opening, reading, writing, and closing of files.
- It enables the reusability of data, portability across different systems, and efficient manipulation of large datasets.
- Two main types of files in C are text files, storing data as ASCII characters, and binary files, storing data in binary format.
- C provides functions like fopen(), fwrite(), fread(), fseek(), fprintf(), and more for file operations.
- Different file opening modes like read, write, append, and read/write are used with fopen() based on the intended operation.
- File pointers serve as references to positions within files and are used extensively in file operations in C.
- Various functions like fclose(), fseek(), rewind(), fprintf(), and fscanf() facilitate file operations in C.
- Reading and writing to binary files involve functions like fwrite() and fread(), which handle data in binary format efficiently.