File Modes in C
File modes decide **how a file will be opened** — for reading, writing, appending, or binary processing.
They control **what operations are allowed** and whether the file will be created or overwritten.
Why File Modes Are Important?
When using fopen(), the second argument specifies the file mode:
FILE *f = fopen("data.txt", "r");
The mode defines:
- Whether the file is opened for reading / writing / both
- If the file will be created automatically
- If existing file content is preserved or deleted
- If data is treated as text or binary
All File Modes in C
Important Notes
- r and r+ need the file to exist.
- w and w+ create a new file and delete old data.
- a and a+ preserve old content.
- Binary modes (b) are used for images, audio, video, and structured data.
- Text modes are default if 'b' is not specified.
Syntax of fopen()
FILE *ptr = fopen("filename.txt", "mode");
If file cannot be opened, fopen() returns NULL.
All File Mode Examples (10 Examples)
/* 1. r – Read Mode */
#include <stdio.h>
int main(){
FILE *f = fopen("data.txt", "r");
if(f == NULL) printf("File not found");
else printf("File opened for reading");
fclose(f);
return 0;
}
/* 2. w – Write Mode (overwrite) */
#include <stdio.h>
int main(){
FILE *f = fopen("new.txt", "w");
fprintf(f, "Hello File");
fclose(f);
return 0;
}
/* 3. a – Append Mode */
#include <stdio.h>
int main(){
FILE *f = fopen("log.txt", "a");
fprintf(f, "\nNew Log Entry");
fclose(f);
return 0;
}
/* 4. r+ – Read + Write */
#include <stdio.h>
int main(){
FILE *f = fopen("info.txt", "r+");
if(f){
fprintf(f, "Updated");
}
fclose(f);
return 0;
}
/* 5. w+ – Read + Write (overwrite) */
#include <stdio.h>
int main(){
FILE *f = fopen("output.txt", "w+");
fprintf(f, "Fresh File");
fclose(f);
return 0;
}
/* 6. a+ – Read + Append */
#include <stdio.h>
int main(){
FILE *f = fopen("log.txt", "a+");
fprintf(f, "\nNew Data");
fclose(f);
return 0;
}
/* 7. rb – Read Binary */
#include <stdio.h>
int main(){
FILE *f = fopen("image.bin", "rb");
if(f) printf("Binary file opened");
fclose(f);
return 0;
}
/* 8. wb – Write Binary (overwrite) */
#include <stdio.h>
int main(){
FILE *f = fopen("raw.bin", "wb");
int x = 100;
fwrite(&x, sizeof(x), 1, f);
fclose(f);
return 0;
}
/* 9. ab – Append Binary */
#include <stdio.h>
int main(){
FILE *f = fopen("data.bin", "ab");
int x = 200;
fwrite(&x, sizeof(x), 1, f);
fclose(f);
return 0;
}
/* 10. r+b – Read/Write Binary */
#include <stdio.h>
int main(){
FILE *f = fopen("marks.bin", "r+b");
if(f){
int n = 99;
fwrite(&n, sizeof(n), 1, f);
}
fclose(f);
return 0;
}