File handling in C is accomplished using file pointers, which provide a way to access and manipulate files. A file pointer is a variable of type FILE*, used to keep track of the position within the file and manage file operations.
Declare a File Pointer:
FILE *fp;
Open a File:
Use the fopen function to open a file. It returns a file pointer or NULL if the operation fails.
fp = fopen("filename.txt", "mode");
Common modes include:
"r": Read (file must exist)"w": Write (creates a new file or truncates existing file)"a": Append (writes data to the end of the file)"r+": Read/Write (file must exist)"w+": Read/Write (creates a new file or truncates existing file)"a+": Read/Write (writes data to the end of the file)Perform File Operations: Use various functions to read from or write to the file.
Writing to a File:
fprintf(fp, "format", data);
fputc('c', fp);
fputs("string", fp);
Reading from a File:
fscanf(fp, "format", &data);
char c = fgetc(fp);
char str[100];
fgets(str, 100, fp);
Close the File:
Use fclose to close the file and release resources.
fclose(fp);
Here's a complete example of writing to and reading from a text file using file pointers.
#include <stdio.h>
int main() {
FILE *fp;
// Open a file for writing
fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
// Write to the file
fprintf(fp, "Hello, World!\n");
fputs("This is a file handling example.\n", fp);
// Close the file
fclose(fp);
// Open the file for reading
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
// Read from the file
char buffer[255];
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
// Close the file
fclose(fp);
return 0;
}
Using file pointers in C allows efficient and flexible file operations, essential for managing persistent data.