File Handling in C
File handling allows programs to store data permanently on disk and read it back when needed. C provides powerful file handling through the standard library (stdio.h).
1. Opening a File in C
Use fopen() function to open a file. Returns FILE* pointer or NULL on failure.
C
FILE *fp = fopen("data.txt", "r");
if(fp == NULL) {
printf("Error opening file!\n");
return 1;
}
| Mode | Description | File must exist? | Creates new file? | Position |
|---|---|---|---|---|
| r | Read | Yes | No | Beginning |
| w | Write | No | Yes (overwrites) | Beginning |
| a | Append | No | Yes (if not exist) | End |
| r+ | Read + Write | Yes | No | Beginning |
| w+ | Read + Write | No | Yes (overwrites) | Beginning |
| a+ | Read + Append | No | Yes | End (for write) |
2. Reading from a File
C
Common reading methods
// Character by character
int ch;
while((ch = fgetc(fp)) != EOF) putchar(ch);
// Line by line
char line[256];
while(fgets(line, sizeof(line), fp)) printf("%s", line);
// Formatted
int age; float salary;
fscanf(fp, "%d %f", &age, &salary);
3. Writing to a File
C
fprintf(fp, "Name: %s Age: %d\n", "Rahul", 25);
fputs("Hello World\n", fp);
fputc('A', fp);
4. Mode 'a' - Append Mode
Opens file for **appending** data at the end. If file doesn't exist → creates it. Never overwrites existing content.
C
FILE *fp = fopen("log.txt", "a");
if(fp) {
fprintf(fp, "[%s] User logged in\n", __TIME__);
}
5. Mode 'a+' - Read + Append
Allows both **reading** and **appending**. Writing always goes to the **end** of file. Useful for logs where you sometimes need to read old data.
Note: fseek() can move read position, but write always appends.
6. Reading and Writing Binary Files
Use modes "rb", "wb", "ab", etc. and functions fread(), fwrite()
C
Writing structure to binary file
struct Student {
char name[50];
int roll;
float marks;
};
struct Student s = {"Aman", 101, 92.5};
FILE *fp = fopen("students.dat", "wb");
fwrite(&s, sizeof(struct Student), 1, fp);
fclose(fp);
// Reading back
struct Student s2;
fp = fopen("students.dat", "rb");
fread(&s2, sizeof(struct Student), 1, fp);
7. File Positioning Functions
ftell(fp)→ returns current position (long)fseek(fp, offset, whence)→ moves pointerrewind(fp)→ moves to beginning- whence values: SEEK_SET (beginning), SEEK_CUR (current), SEEK_END (end)
C
fseek(fp, 0, SEEK_END); // go to end
long size = ftell(fp); // file size
fseek(fp, 0, SEEK_SET); // back to start
fseek(fp, -10, SEEK_END); // last 10 bytes
8. Closing a File
Always close files using fclose() to free resources and flush buffers.
C
if(fclose(fp) == 0)
printf("File closed successfully\n");
else
printf("Error closing file!\n");
9. Command Line Arguments
Access arguments passed while running program using main(int argc, char *argv[])
C
Copy file content (like simple cp command)
#include <stdio.h>
int main(int argc, char *argv[]) {
if(argc != 3) {
printf("Usage: %s source.txt destination.txt\n", argv[0]);
return 1;
}
FILE *src = fopen(argv[1], "rb");
FILE *dest = fopen(argv[2], "wb");
if(!src || !dest) {
printf("Error opening files!\n");
return 1;
}
char buffer[1024];
size_t bytes;
while((bytes = fread(buffer, 1, sizeof(buffer), src)) > 0)
fwrite(buffer, 1, bytes, dest);
fclose(src);
fclose(dest);
printf("File copied successfully!\n");
return 0;
}
Codecrown