C File Handling Tutorial
C file handling allows you to work with files, such as opening, reading, writing, and closing them. This tutorial will walk you through basic file operations in C.
1. Opening a File
To open a file, use the fopen function. The syntax is:
FILE *fopen(const char *filename, const char *mode);
Common modes include "r" (read), "w" (write), and "a" (append).
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // Open file for writing
if (file == NULL) {
printf("File could not be opened\\n");
return 1;
}
fclose(file); // Close file
return 0;
}
2. Reading from a File
You can read from a file using functions like fgetc, fgets, or fread. The simplest form is fgetc, which reads one character at a time:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r"); // Open file for reading
char ch;
if (file == NULL) {
printf("File could not be opened\\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) { // Read character by character
putchar(ch); // Print the character
}
fclose(file);
return 0;
}
3. Writing to a File
To write to a file, you can use fputc, fputs, or fwrite. Here's how to use fputs to write a string:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // Open file for writing
if (file == NULL) {
printf("File could not be opened\\n");
return 1;
}
fputs("Hello, World!", file); // Write to file
fclose(file);
return 0;
}
4. Closing a File
Once you're done with a file, close it using the fclose function:
int fclose(FILE *file);
It ensures all data is written and resources are released.
5. Checking for Errors
To check if a file operation is successful, you can use the feof and ferror functions:
if (feof(file)) {
printf("End of file reached\\n");
} else if (ferror(file)) {
printf("Error reading the file\\n");
}
6. Conclusion
File handling in C is straightforward but requires attention to details such as opening, reading, writing, and closing files. Always ensure to close a file after you're done with it to prevent data loss and resource leaks.