file writing

B

bob

Is there a way to overwrite a random byte in a file using FILE without
rewriting the whole file?
 
V

Victor Bazarov

Is there a way to overwrite a random byte in a file using FILE without
rewriting the whole file?

Yes. Open the file for reading/writing, then use fseek to get to the
position where you want to write, then use fwrite, then close it. IIRC
on some platforms you could end up with a truncated file unless you
open it for both reading and writing, you will need to check with your
documentation.

V
 
K

Kern

But it's quite classic way to moditfy the binary file.
How can we do this in a modern cpp way?
 
T

Tribal-Tec

The modern cpp way would be the use of fstream;

std::eek:fstream myFile; // or fstream for both writing and reading
myFile.open( "filename", std::ios_base::binary | std::ios_base::eek:ut );

now with seekg method you can place the write cursor to modify your
desired byte.

Regards
 
C

Chris Theis

Kern said:
But it's quite classic way to moditfy the binary file.
How can we do this in a modern cpp way?

Surely you could use streams but what will you gain in this case?

Cheers
Chris
 
B

BobR

Tribal-Tec wrote in message
The modern cpp way would be the use of fstream;
std::eek:fstream myFile; // or fstream for both writing and reading
myFile.open( "filename", std::ios_base::binary | std::ios_base::eek:ut );

now with seekg method you can place the write cursor to modify your
desired byte.

The 'g' in 'seekg' means 'get' to me. Use 'seekp' to 'put'.

std::eek:fstream MyFile("MyFile.txt", std::ios_base::binary );
if(!MyFile){ std::cout<<"\n ofstream FAILED"<<std::endl; /*exit(1);*/}
std::cout<<"ofstream MyFile.tellp() = "<<MyFile.tellp()<<std::endl;
MyFile.seekp(10, std::ios::end);
std::cout<<"MyFile.seekp(10, end) MyFile.tellp() ="
<<MyFile.tellp()<<std::endl;
MyFile.seekp(10, std::ios::beg);
std::cout<<"MyFile.seekp(10, beg) MyFile.tellp() ="
<<MyFile.tellp()<<std::endl;
MyFile.close();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top