7.1) File Handling in C
Table of Contents
File Handling in C
File handling in C allows you to work with files on your computer’s storage. You can read data from files (like reading a book) and write data to files (like writing in a journal). C provides functions and tools to make file operations easy.
Opening a File in C
To work with a file, you need to open it. You can open a file in different modes: for reading, writing, or both.
Example: Opening a File for Writing
#include <stdio.h>
int main() {
FILE *filePointer;
// Open 'example.txt' in write mode
filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
printf("File cannot be opened.\n");
return 1; // Exit the program
}
// Do something with the file
// Close the file
fclose(filePointer);
return 0;
}
Writing to a File in C
Once a file is opened for writing, you can use functions like fprintf
to write data to it.
Example: Writing to a File
#include <stdio.h>
int main() {
FILE *filePointer;
filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
printf("File cannot be opened.\n");
return 1;
}
fprintf(filePointer, "Hello, File Handling in C!\n");
fprintf(filePointer, "Welcome to the world of programming.\n");
fclose(filePointer);
return 0;
}
After running this program, you’ll find a file named example.txt
in the same directory with the written content.
Reading from a File in C
You can open a file for reading and use functions like fscanf
to read data from it.
Example: Reading from a File
#include <stdio.h>
int main() {
FILE *filePointer;
char content[100];
filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
printf("File cannot be opened.\n");
return 1;
}
while (fscanf(filePointer, "%s", content) != EOF) {
printf("%s ", content);
}
fclose(filePointer);
return 0;
}
This program reads the content of example.txt
and prints it on the screen.
Output:
Hello, File Handling in C!
Welcome to the world of programming.
Appending to a File in C
You can open a file in append mode to add data to the end of an existing file.
Example: Appending to a File
#include <stdio.h>
int main() {
FILE *filePointer;
filePointer = fopen("example.txt", "a");
if (filePointer == NULL) {
printf("File cannot be opened.\n");
return 1;
}
fprintf(filePointer, "\nAppending to the file.\n");
fclose(filePointer);
return 0;
}
After running this program, the example.txt
file will have additional content at the end.
File handling in C allows you to work with files, which is essential for tasks like reading input from files, storing data, and generating reports. Remember to always close files using fclose
after you’re done working with them. This prevents data corruption and frees up resources.