File Modes in C
File Modes in C
Introduction
File modes in C define how a file should be opened and used.
👉 They control whether you can:
- Read
- Write
- Append data
What are File Modes?
File modes are:
👉 Options used with fopen() to specify file operations
Syntax
FILE *fp = fopen("filename", "mode");
Types of File Modes
Basic File Modes
| Mode | Description |
|---|---|
| r | Read (file must exist) |
| w | Write (creates/overwrites file) |
| a | Append (adds data) |
Advanced File Modes
| Mode | Description |
|---|---|
| r+ | Read & Write (file must exist) |
| w+ | Read & Write (creates new file) |
| a+ | Read & Append |
Binary File Modes
| Mode | Description |
|---|---|
| rb | Read binary |
| wb | Write binary |
| ab | Append binary |
Example: Using Different Modes
#include <stdio.h>
int main() {
FILE *fp;
// Write mode
fp = fopen("test.txt", "w");
fprintf(fp, "Hello\n");
fclose(fp);
// Append mode
fp = fopen("test.txt", "a");
fprintf(fp, "World\n");
fclose(fp);
// Read mode
char str[50];
fp = fopen("test.txt", "r");
fgets(str, sizeof(str), fp);
printf("%s", str);
fclose(fp);
return 0;
}
Output
Hello
👉 File contains:
Hello
World
Important Notes
-
r→ file must exist -
w→ deletes old content -
a→ adds data at end -
+→ allows both read & write
Common Mistakes
- ❌ Using wrong mode
- ❌ Not closing file
-
❌ Data loss with
wmode - ❌ Not checking file pointer
Pro Tips
- ✔ Choose correct mode carefully
-
✔ Use
ato avoid data loss - ✔ Always close files
- ✔ Handle errors properly
Conclusion
File modes are essential for controlling file operations in C. Choosing the right mode ensures proper data handling.
Master file modes for efficient file management.
👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.
Comments
Post a Comment