Click to See Complete Forum and Search --> : how to change single chars by overwriting


nichtswissender
June 12th, 2002, 06:45 AM
hi

i have a problem by writing into a file in binary mode...

i want to overwrite single characters in given positions...

so far iīm using that code:

FILE *out;
out = fopen(<filename>, "ab"); // a for append, b for binary
fseek (out, <intPosition>, SEEK_CUR);
fputc(<char>, out);

the problem with this technique is, that the code doesn't overwrite existing characters, but appends everything at the end of the file (although i have set the filepointer to the correct position)...

using "wb" instead of "ab" when opening the file results in overwriting the whole file...

does anybody know a correct (and maybe quick) way to handle this problem ?

thx a lot
nichtswissender (<-- knownothingman ;))

sjeng
June 12th, 2002, 07:07 AM
Why don't you just read the file in to the memory and change it and write it to disk like a new file?
That would be a simple sollution....

nichtswissender
June 12th, 2002, 07:19 AM
because i have to change up to 600 files. inc. database-files which can have up to 80MB. And i only have to change a few bytes per file.

sjeng
June 12th, 2002, 07:33 AM
I don't know which development envirement you are using, but Visual C++ has the CFile class that has a read-write mode...
I don't know what facilities ansi C++ has :(

nichtswissender
June 12th, 2002, 07:37 AM
i'm working on Borland Builder...

the FILE * object works similar to the CFILE * object from visual...

there also exists the read-write mode, but when i open the file in write-mode, the whole file gets overwritten... when i open the file in append-mode, everything is appended at the end of the file...
:(

Philip Nicoletti
June 12th, 2002, 11:35 AM
Maybe this will do what you want




#include <iostream>
#include <fstream>
#include <ios>

int main()
{
std::fstream myfile("myfile.dat",std::ios::in|std::ios::out|std::ios::binary);

myfile.seekg(0); // goto start of file
myfile.put('c'); // and replace it with 'c'

myfile.seekg(8); // goto the ninth character in file
myfile.put('Q'); // and replace it with 'Q'

myfile.seekg(0,std::ios::end); // goto the end of the file
// start appending as usual
myfile.write("append",6);

return 0;
}

nichtswissender
June 13th, 2002, 02:03 AM
itīs working now :D

ThX

Ungi
June 13th, 2002, 02:54 AM
you also could have used your method with the opening mode "r+b"!

nichtswissender
June 13th, 2002, 03:12 AM
so... here is the next problem...

when i have edited the files i have to cut off a few bytes at the end.

how can i delete the last few bytes? at the moment i only can overwrite them and I canīt find a way to delete them after i have set the EOF byte '\0'.