File handling in the C programming language involves working with files, such as creating, opening, reading, writing, and closing them. Let's break down the process and provide examples for each step.
1. C Files:
a. Introduction:
In C, a file is a collection of data that is stored on secondary storage (usually on a hard disk). C provides standard library functions to handle files. The two primary modes for file handling are text mode and binary mode.
2. Create and Write to a File:
a. Include Header Files:
You need to include the necessary header files.
b. Declare File Pointer:
You declare a file pointer variable, which will be used to interact with the file.
c. Open the File:
Use the fopen()
function to open or create a file. It returns a pointer to the file.
d. Write to the File:
Use functions like fprintf()
or fputc()
to write data to the file.
e. Close the File:
Use fclose()
to close the file when you're done writing.
#include
int main() {
FILE *file; // Declare a file pointer
file = fopen("example.txt", "w"); // Open or create a file in write mode
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
fprintf(file, "Hello, World!\n"); // Write data to the file
fclose(file); // Close the file
return 0;
}
3. Read a File:
a. Include Header Files:
Include the necessary header files.
b. Declare File Pointer:
Declare a file pointer.
c. Open the File:
Use fopen()
in read mode ("r").
d. Read from the File:
Use functions like fscanf()
or fgetc()
to read data from the file.
e. Close the File:
Use fclose()
when you're done reading.
#include
int main() {
FILE *file; // Declare a file pointer
file = fopen("example.txt", "r"); // Open the file in read mode
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer); // Print the content of the file
}
fclose(file); // Close the file
return 0;
}
File Handling Properties:
Modes:
- "r" - Read
- "w" - Write
- "a" - Append
- "rb" - Read in binary mode
- "wb" - Write in binary mode
- "ab" - Append in binary mode
File Pointers:
FILE*
is the data type for file pointers.
File Functions:
fopen()
: Opens a file.
fclose()
: Closes a file.
fprintf()
: Write formatted data to a file.
fscanf()
: Read formatted data from a file.
fputc()
: Write a character to a file.
fgetc()
: Read a character from a file.