File handling is a fundamental aspect of C programming, enabling you to interact with external files for data input and output. In this comprehensive guide, we’ll explore file handling in C, focusing on working with both text and binary files. Real-world examples with outputs will illustrate the concepts and help you become proficient in handling files of various types in C.
Introduction to Text and Binary Files
File handling in C allows for interaction with two primary file types: text files and binary files. Understanding the differences between these file types and how to work with them is essential for efficient data manipulation.
Text Files
Text files are human-readable files that store data in plain text format. They are commonly used for storing and exchanging information in a format that can be easily understood by both humans and machines.
Example: Reading and Writing Text Files
#include <stdio.h>
int main() {
FILE *textFile;
char ch;
// Open a text file for reading
textFile = fopen("sample.txt", "r");
if (textFile == NULL) {
printf("Text file not found or unable to open.\n");
return 1;
}
// Read and print the contents character by character
while ((ch = fgetc(textFile)) != EOF) {
printf("%c", ch);
}
// Close the text file
fclose(textFile);
// Open a text file for writing
textFile = fopen("output.txt", "w");
if (textFile == NULL) {
printf("Unable to create or open the text file for writing.\n");
return 1;
}
// Write data to the text file
fprintf(textFile, "This is a sample text written to a text file.\n");
// Close the text file
fclose(textFile);
return 0;
}
Binary Files
Binary files store data in a format that is not human-readable. They are used for storing various types of data, including images, audio, and structured records.
Example: Reading and Writing Binary Files
#include <stdio.h>
int main() {
FILE *binaryFile;
// Open a binary file for writing
binaryFile = fopen("data.bin", "wb");
if (binaryFile == NULL) {
printf("Unable to create or open the binary file for writing.\n");
return 1;
}
// Write binary data to the file
int data[] = {1, 2, 3, 4, 5};
fwrite(data, sizeof(int), sizeof(data) / sizeof(int), binaryFile);
// Close the binary file
fclose(binaryFile);
// Open a binary file for reading
binaryFile = fopen("data.bin", "rb");
if (binaryFile == NULL) {
printf("Binary file not found or unable to open.\n");
return 1;
}
// Read and print binary data from the file
int readData[5];
fread(readData, sizeof(int), 5, binaryFile);
for (int i = 0; i < 5; i++) {
printf("%d ", readData[i]);
}
// Close the binary file
fclose(binaryFile);
return 0;
}
Output:
1 2 3 4 5
Working with text and binary files is essential for tasks such as:
- Reading and writing configuration files.
- Storing and retrieving non-textual data like images and audio.
- Handling structured data in binary format for performance-critical applications.