2

I'm simply trying to read a small 1KB binary file into a buffer and then write the buffer back to the disk. It seems that for some files the outputfile is completely different from the Inputfile, what am I doing wrong? Thank you very much.

std::ifstream myfile; myfile.open (testinput.rar); myfile.seekg (0, myfile.end); filesize = myfile.tellg(); myfile.seekg (0, myfile.beg); char *mybuffer= new char[filesize]; myfile.read(mybuffer,filesize); myfile.close(); ofstream myfile3; myfile3.open ("testoutput.rar"); for(unsigned int i=0; i<filesize; i++) myfile3 << mybuffer[i]; myfile3.close(); 
4
  • 1
    It's been a while, but I think the file variable needs to be set to binary mode for binary data... Commented Oct 23, 2013 at 14:58
  • 1
    Should there be quotes round the parameter in myfile.open (testinput.rar);? Can't imagine that would even build. Commented Oct 23, 2013 at 14:59
  • @user1158692 Yes, of course there should be quotes around the file name parameter. cplusplus.com/doc/tutorial/files Commented Oct 23, 2013 at 15:06
  • possible duplicate of Reading and writing binary file Commented Oct 24, 2013 at 8:43

2 Answers 2

1

You have to open the file as binary.

myfile.open ("testinput.rar", std::ios::binary); 
Sign up to request clarification or add additional context in comments.

Comments

1

myfile3 should be opened in binary mode:

myfile3.open("testoutput.rar", ios::out | ios::binary); 

Additionally, you may want to consider using write() to modify files:

myfile3.write(mybuffer[i], sizeOfBuffer); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.