How can I write to a file multiple times using fwrite without affecting the previous writes?
The method shown below accepts a file name, buffer and offset. The method opens the file in reading/writing mode and writes the content of the buffer at offset.
Code:
int writeData(char *filename, char *buffer, int offset){
FILE *fp;
fp = fopen(filename, "w+"); // this truncates the file :(
fseek(fp, offset, SEEK_SET);
fwrite(buffer, sizeof(char), strlen(buffer), fp);
int pos = ftell(fp);
fclose(fp);
return pos;
}
void main(){
writeData("alpha", "ABCDEFGH", 0);
writeData("alpha", "WXYZ", 2);
}
// content of file: [^@^@WXYZ]
However, the intended behavior should be "ABWXYZGH." Using the "r+" mode gives the intended behavior if the file exists, which is not always the case. As a workaround, I try to open in "r+" first and create the file if it does not exist:
Code:
int writeData(char *filename, char *buffer, int offset){
FILE *fp;
fp = fopen(filename, "r+");
if (fp == NULL) {
fp = fopen(filename, "w");
if (fp) {
fclose(fp);
fp = fopen(filename, "r+");
} else // do not have sufficient permission
return -1;
}
fseek(fp, offset, SEEK_SET);
fwrite(buffer, sizeof(char), strlen(buffer), fp);
int pos = ftell(fp);
fclose(fp);
return pos;
}
I am not sure that's the right way of doing it.