By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,148 Members | 1,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,148 IT Pros & Developers. It's quick & easy.

file writing

P: n/a
bob
Is there a way to overwrite a random byte in a file using FILE without
rewriting the whole file?

Dec 10 '05 #1
Share this Question
Share on Google+
6 Replies


P: n/a
bo*@coolgroups.com wrote:
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
Dec 10 '05 #2

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

Dec 10 '05 #3

P: n/a
bob
is it fopen("file", "r+b");

???

Dec 10 '05 #4

P: n/a
The modern cpp way would be the use of fstream;

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

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

Regards

Dec 10 '05 #5

P: n/a

Tribal-Tec wrote in message
<11**********************@g44g2000cwa.googlegroups .com>...
The modern cpp way would be the use of fstream;
std::ofstream myFile; // or fstream for both writing and reading
myFile.open( "filename", std::ios_base::binary | std::ios_base::out );

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::ofstream 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();

--
Bob R
POVrookie
Dec 10 '05 #6

P: n/a

"Kern" <ke********@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
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
Dec 10 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.