Archived

This topic is now archived and is closed to further replies.

kuphryn

Reading/Writing in Binary

Recommended Posts

Hi, I have a complicated (to me) problem reading/Writing data in binary. Here is what I am doing. For example let say a text file has the following: File: test.txt ----------------- 1234a5678b9 ----------------- Here is what I am doing: istream inData; ostream outData; inData.open("test.txt", ios::in | ios::binary); outData.open("modified.txt", ios::out | ios::binary); inData.seekg(0, ios::end); int size = inData.tellg(); char *temp; temp = new char[size + 2]; inData.read(reinterpret_cast(temp), size); temp[size + 1] = ''c''; temp[size + 2] = ''d''; outData.write(reinterpret_cast(temp), (size + 2); ----------------------------------------------------- The code above should work okay. As you can see, all I am doing is reading data from a file, add two characters "c" and "d" and then writing it back to the file. Everything is fine. Now, let say I read the modified file back. Here is what I am doing: istream modData; ostream weird; modData.open("modified.txt", ios::in | ios::binary); weird.open("hungry", ios::out | ios::binary); inData.seekg(0, ios::end); int size = inData.tellg(); char *temp, charA, charB; temp = new char[size]; inData.read(reinterpret_cast(temp), size); charA = temp[size - 2]; charB = temp[size - 1]; ----------------------------------------------------- Do you see what I am trying to doing? 1)read fileA in binary 2)save data from fileA to tempX 3)add characters to tempY 4)write temp to fileB ----------------------- 1)read fileB in binary 2)save data from fileB to tempZ 3)extract ONLY those characters I added to tempX from tempZ ----------------------- The method I use to extract the added characters from the modified file after I read it back is subscript. I assume let say temp[5] is ''a''. When I read the data back, I look at temp[5]. My question is when you read a file in binary, add characters to it in specific spaces and write it to modified file, is it possible to read the data from the modified file and extract those characters you added via assumption subscript? How are data saved when you read and write in binary? Thanks, Kuphryn

Share this post


Link to post
Share on other sites
When you save in binary, the data is send to the disk without any modifications. Especially, numbers are not converted to ascii representation, but saved as the appropriate binary pattern, as are structs. So, as long as you know what the pattern is, you can retrieve your data by looking in the right place (where you wrote it in the first place).

Share this post


Link to post
Share on other sites
Okay. Thanks.

I have tried reading data in binary, add data to the same container it was read into and then write it back in binary. I know the position, but I cannot extract that same data I originally added when I read the file the second time. Weird.

Kuphryn

Share this post


Link to post
Share on other sites