Introduction
In this lesson, we will delve into file handling in C. Understanding how to manage files is a vital skill for any programmer, as it allows us to read from and write to files, making our programs capable of persistent data storage. We will cover file operations such as opening, closing, reading, and writing, as well as explore standard file handling functions along with error handling techniques. Finally, we will discuss file positioning functions that enable us to navigate through files efficiently.
File Operations in C
Basic Operations
File handling in C involves several fundamental operations, which include:
- Opening a file: This is the first step before performing any operations on a file. The
fopenfunction is used here. - Closing a file: Once operations are complete, it’s important to properly close the file using
fcloseto free resources. - Reading from a file: We can access data within a file using the
freadfunction. - Writing to a file: To save data, we use the
fwritefunction.
Code Example of File Operations
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "w"); // Open file for writing
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, File Handling in C!\n"); // Write to the file
fclose(file); // Close the file
return 0;
}
Program Explanation:
- The program opens a file named
example.txtin write mode. - If the file can't be opened (e.g., due to permission issues), it prints an error message.
- It writes a string to the file and then closes the file.
Output: (No output to console, but example.txt will contain)
Hello, File Handling in C!
Standard File Handling Functions
-
fopen: Used to open a file.
- Syntax:
FILE *fopen(const char *filename, const char *mode); - Modes include:
"r"(read),"w"(write),"a"(append).
- Syntax:
-
fclose: Closes a file stream.
- Syntax:
int fclose(FILE *stream);
- Syntax:
-
fread: Reads data from a file.
- Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
- Syntax:
-
fwrite: Writes data to a file.
- Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
- Syntax:
Text vs. Binary File Handling
Text Files
Text files store data in human-readable format.
- Use functions like
fgetsfor reading lines andfputsto write lines.
Binary Files
Binary files store data in a format that is not human-readable. This is often used for non-text files.
- Functions like
freadandfwriteare commonly used.
Code Example: Binary File Handling
#include <stdio.h>
#include <stdlib.h>
struct Data {
int value;
};
int main() {
struct Data data = { 123 }; // Sample data
FILE *file = fopen("data.bin", "wb");
fwrite(&data, sizeof(data), 1, file);
fclose(file);
return 0;
}
Program Explanation:
- This program writes a structure to a binary file named
data.bin. It opens the file in binary write mode ("wb") and writes thedatastructure.
Output: (No output directly visible. A binary file data.bin is created.)
Error Handling in File Operations
Effective error handling is critical. Always check if the file was opened successfully by checking the return value of fopen. If it returns NULL, an error occurred. Always include error checking for file operations to ensure the program behaves as expected under all circumstances.
Code Example for Error Handling
int main() {
FILE *file;
file = fopen("non-existent-file.txt", "r"); // Attempt to open a non-existing file
if (file == NULL) {
perror("Error opening file"); // Print error message
return 1;
}
fclose(file);
return 0;
}
Output:
The output will display a system error message indicating that the file could not be opened.
File Positioning Functions
File positioning allows you to navigate through files:
- fseek: Moves the file pointer to a specific location.
- Syntax:
int fseek(FILE *stream, long offset, int whence);
- Syntax:
- ftell: Returns the current position of the file pointer.
- Syntax:
long ftell(FILE *stream);
- Syntax:
- rewind: Moves the file pointer back to the beginning of the file.
- Syntax:
void rewind(FILE *stream);
- Syntax:
Code Example: Using Positioning Functions
#include <stdio.h>
int main() {
FILE *file;
file = fopen("example.txt", "r");
fseek(file, 0, SEEK_END); // Move to the end
long size = ftell(file); // Get current position
rewind(file); // Move back to the beginning
printf("File size: %ld bytes\n", size);
fclose(file);
return 0;
}
Program Explanation:
- The program opens
example.txt, moves the pointer to the end, retrieves the size, rewinds to the start, and prints the file size.
Output:
File size: <size> bytes
(Where <size> is the byte size of the file.)
Summary / Key Takeaways
- File Operations: Understand how to open, close, read, and write to files.
- Standard Functions: Familiarize yourself with
fopen,fclose,fread, andfwrite. - Text vs. Binary: Differentiate file handling techniques for text and binary files.
- Error Handling: Implement error checks for all file operations to ensure program resilience.
- File Positioning: Utilize
fseek,ftell, andrewindfor efficiently navigating file content. - Practical Application: Apply techniques in real-world scenarios to manage file data effectively.
- Dynamic Decision Making: Understand how pointers enhance file handling within functions for dynamic scenarios.