Reputation: 251
Just as the title asks, how do I use fopen to write data to a specific section of a file while pushing the existing data down without erasing it. I have used fseek along with SEEK_SET and SEEK_CUR and so far I am able to get new data to be written in the correct section of the file, however, the first few lines of existing data get deleted.
Upvotes: 1
Views: 391
Reputation: 138051
I must admit I rarely use fopen
for "complex" manipulations of data and appending stuff in the middle of a file is not something I frequently do. Usually, when I need that usage pattern, I just override the whole file with the new data. So there might be a clever way to append data in the middle of a file, but I don't know it: I'm fairly sure you can only override.
The simplest way I can think of to append in the middle of a file is the following: find the place you need to write, find how many bytes you have to relocate, find the length of the data to insert, move the write cursor to (place you need to write + length), overwrite the data from that point with the data you need to relocate, then write what you needed to write in the first place.
#include <stdio.h>
#include <stdlib.h>
size_t finsert(void* data, size_t length, FILE* fp)
{
const long writePosition = ftell(fp);
fseek(fp, 0, SEEK_END);
const long fileSize = ftell(fp);
const long relocatedDataSize = fileSize - writePosition;
char* dataToRelocate = malloc(relocatedDataSize);
fseek(fp, writePosition, SEEK_SET);
fread(dataToRelocate, relocatedDataSize, 1, fp);
fseek(fp, writePosition + length, SEEK_SET);
fwrite(dataToRelocate, relocatedDataSize, 1, fp);
free(dataToRelocate);
fseek(fp, writePosition, SEEK_SET);
return fwrite(data, length, 1, fp);
}
Note that you need read and write access to the file, just write won't cut it.
Also, as Cole Johnson mentioned, if you're using a file "like a database", consider using SQLite. It handles all that kind of crazy stuff for you and makes a lot of things a lot simpler.
Upvotes: 3
Reputation: 229108
The file systems you find on normal desktop and server operating systems does not support insertion, so this can't be done.
You have to rewrite the file.
Upvotes: 3