C file handling
Created By: chatGPT
File handling in C programming allows us to read, write, and manipulate files on disk. This process involves using various file functions defined in the
<stdio.h>
library. The essential concepts include opening a file, performing operations (like reading or writing), and closing the file once done to free resources. Here’s how you can handle files in C.// Include the standard I/O library
#include <stdio.h>
int main() {
FILE *file;
char data[100];
// Opening a file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Writing to the file
fprintf(file, "Hello, World!\n");
// Closing the file
fclose(file);
return 0;
}
To read from a file, you can open it in read mode and use functions like
fgets()
or fscanf()
. Always ensure to check whether the file was opened successfully to avoid segmentation faults or unexpected behavior.// Include the standard I/O library
#include <stdio.h>
int main() {
FILE *file;
char buffer[100];
// Opening a file in read mode
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Reading from the file
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer);
}
// Closing the file
fclose(file);
return 0;
}
When working with files, you should also be familiar with the different modes you can use when opening a file:
r
for read, w
for write (which creates a new file or truncates an existing one), a
for append, and r+
for updating (reading and writing). Understanding these modes will help you manipulate files effectively.// Include the standard I/O library
#include <stdio.h>
int main() {
FILE *file;
// Opening a file in append mode
file = fopen("example.txt", "a");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Writing additional data to the file
fprintf(file, "Appending new line.\n");
// Closing the file
fclose(file);
return 0;
}
Error handling is crucial in file operations. Always check if the file pointer is
NULL
after attempting to open a file. This practice ensures that your program can handle errors gracefully without crashing unexpectedly.// Include the standard I/O library
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
// Attempting to open a nonexistent file
file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Error opening file"); // Print error message
exit(EXIT_FAILURE); // Exit with failure status
}
// Closing the file (this line won't be reached)
fclose(file);
return 0;
}