File handling in C is crucial for tasks that involve storing data persistently on the disk. It allows you to create, read, write, and manipulate files. Here's a comprehensive guide to file handling in C, including examples for various file operations.
1. Opening a File: Use fopen().
2. Reading from a File: Use functions like fgetc(), fgets(), and fscanf().
3. Writing to a File: Use functions like fputc(), fputs(), and fprintf().
4. Closing a File: Use fclose().
5. Positioning in a File: Use functions like fseek(), ftell(), and rewind().
| Function | Description |
|---|---|
| fopen() | Opens a file |
| fprintf() | Writes formatted data to a file |
| fscanf() | Reads formatted data from a file |
| fputc() | Writes a character to a file |
| fgetc() | Reads a character from a file |
| fclose() | Closes the file |
| fseek() | Sets the file pointer to a given position |
| fputw() | Writes an integer to a file |
| fgetw() | Reads an integer from a file |
| ftell() | Returns the current file position |
| rewind() | Sets the file pointer to the beginning of the file |
| Mode | Description |
|---|---|
| r | Read mode (text file). |
| w | Write mode (text file). Creates a new file or truncates an existing file. |
| a | Append mode (text file). Adds to the end of an existing file. |
| r+ | Read and write mode (text file). |
| w+ | Read and write mode (text file). Creates or truncates the file. |
| a+ | Read and write mode (text file). Appends to the end of the file. |
| rb | Read mode (binary file). |
| wb | Write mode (binary file). |
| ab | Append mode (binary file). |
| rb+ | Read and write mode (binary file). |
| wb+ | Read and write mode (binary file). |
| ab+ | Read and write mode (binary file). Appends to the end of the file. |
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Open file for writing
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "Hello, world!\\n");
fclose(fp);
return 0;
}
To close a file, use the fclose() function.
int fclose(FILE *fp);
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
char ch;
if (fp != NULL) {
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
}
return 0;
}
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w");
if (fp != NULL) {
fputc('A', fp);
fclose(fp);
}
return 0;
}