I'm trying to write to a new file with 'wb' mode at given offset using function owrite provided below, but every time it overwrite all bytes before the offset. Using windows 10, visual studio 2019 16.0.3.
Offset is positive number and outside file bounds (since it's a new file). count == 64000 == size of buf.
I've tried to use lseek/_lseek write/_write (with fileno) but ended up with similar result. owrite don't return -1, also checked output of fwrite and everything seems fine. What is the right way to perform this operation?
int owrite(FILE* fd, char* buf, size_t count, int offset)
{
if (fseek(fd, offset, SEEK_SET) != 0) {
return -1;
}
fwrite((char*)buf, sizeof(char), count, fd);
fseek(fd, 0, SEEK_SET);
return 0;
}
Also here is function that calls owrite:
void insert_chunk(byte* buffer, int len, char* filename, long offset)
{
FILE* builded_file = fopen(filename, "wb");
owrite(builded_file, buffer, len, offset);
fclose(builded_file);
}
//byte is unsigned char
You are telling it to discard existing contents when you open the file. You want "r+", not "w" (or, "r+b" in your case).
From http://www.cplusplus.com/reference/cstdio/fopen/:
"w" write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
Note that "r+" only works if the file already exists. If you don't know whether the file exists, you may need to check that first, and open with "w" or "w+" if it doesn't exist.
If you really want to add to the end of the file, and not to an offset in the middle, you could use "a" or "a+", which will create the file if it does not exist.