Friday 15 February 2013

c++ - Missing data when reading/writing to stream -


Here's the full example - compile and run, writes the contents of the map into the file and reads it properly: / P>

 Add  # & lt; Map & gt; # Include & lt; Fstream & gt; # Include & lt; Iostream & gt; using namespace std; Int main (int argc, char * argv []) {std :: string fname ("test.bin"); Std :: map & lt; Unsigned, unsigned & gt; TestMap; TestMap [0] 103 =; TestMap [1] 2 =; TestMap [5] 26 =; TestMap [22] 4 =; Std :: offstream output (fname.c_str (), std :: ios_base :: binary | std :: ios_base :: trunc); (Std :: map & lt; unsigned, unsigned & gt; :: iterator iter = testMap.begin (); iter! = TestMap.end (); ++ iter) {unsigned temp = iter-> first; Output.write ((const char *) and temporarily, size (temp)); Unsigned temp1 = iter-> second; Output.write (const char *) and temp1, sizeof (temp1)); Std :: cerr & lt; & Lt; Temp & lt; & Lt; "" & Lt; & Lt; Temp1 & lt; & Lt; "" & Lt; & Lt; Std :: endl; } Std :: cerr & lt; & Lt; "Bytes written .........." & lt; & Lt; Output.tellp () & lt; & Lt; "Map Size" & lt; & Lt; TestMap.size () & lt; & Lt; Std :: endl; Output.flush (); Output.close (); Std :: ifstream input (fname.c_str ()); // Get the length of the file: input.seekg (0, input.end); Unsigned stream size = input.tellg (); Input.seekg (0, input.beg); Char * buff = new four [streamSize]; Input.read (buff, streamSize); Serie Lieutenant; & Lt; "Input size ..." & lt; & Lt; Stream size & lt; & Lt; Endl; Serie Lieutenant; & Lt; "Read bytes ..........." & lt; & Lt; Input.gcount () & lt; & Lt; Endl; :: getchar (); Return 0; }   

This gives the following output:

  0 103 1 2 5 26 22 4 bytes written .......... 32, Map size 4 input size ...... 32 read bytes ........... 20   

The question is why do not match bytes read bytes How to read / write accounts, and entire maps

The PS Online Compiler gives me the expected output of 32 read bytes, I get wrong output while compiling with Visual Studio 2010 profession.

Make sure you open the file as a binary file.

No comments:

Post a Comment