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:

All File Modes in C

Mode → Meaning
-------------------------------------------------------
r → Read only (file must exist)
w → Write only (creates new, deletes old)
a → Append only (adds data at end)
r+ → Read + Write (file must exist)
w+ → Read + Write (overwrites file)
a+ → Read + Append (keeps old, adds new)
rb → Read binary
wb → Write binary (creates new)
ab → Append binary
r+b / rb+ → Read + Write binary
w+b / wb+ → Read + Write binary (overwrite)
a+b / ab+ → Read + Append binary

Important Notes

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;
}