Open file in append mode

If you open a file by writing mode then every time old data will be replaced by new data.

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("c:\\test.txt", "w");
    fprintf(fp, "KUET EEE");
    fclose(fp);
    return 0;  
}

Run the above code & check ‘test.txt’ file which is located in your ‘C’ drive.

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("c:\\test.txt", "w");
    fprintf(fp, "KUET CSE");
    fclose(fp);
    return 0;  
}

Run the above code and check test.txt file located your ‘C’ drive.

During first check you have seen:
KUET EEE

During second check you have seen:
KUET CSE

That proves “KUET EEE” has been replaced by “KUET CSE”.

So how can we write new data keeping the old? We can do this by append mode. ‘a’ stands for append mode. Now run the following code and check your test.txt file again:

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("c:\\test.txt", "w");
    fprintf(fp, "\n KUET EEE");
    fclose(fp);
    return 0;  
}

If you run the above three programs sequentially then at last check, you will see:
KUET CSE
KUET EEE


Next Previous