1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
std::ostream& write_string( std::ostream& stm, const std::string& str )
{
// write the size of the string (number of characters in the string)
const std::size_t nbytes = str.size() ;
stm.write( reinterpret_cast<const char*>( std::addressof(nbytes) ), sizeof(nbytes) ) ;
// write the characters in the string
return nbytes ? stm.write( str.data(), nbytes ) : stm ;
}
std::istream& read_string( std::istream& stm, std::string& str )
{
// read the size of the string (number of characters in the string)
std::size_t nbytes = 0 ;
if( stm.read( reinterpret_cast<char*>( std::addressof(nbytes) ), sizeof(nbytes) ) )
{
// resize the string and read the characters into the string
str.resize(nbytes) ;
if(nbytes) stm.read( const_cast<char*>( str.data() ), nbytes ) ;
}
return stm ;
}
std::ostream& write_strings( std::ostream& stm, const std::vector<std::string>& strings )
{
for( const std::string& str : strings ) write_string( stm, str ) ;
return stm ;
}
std::vector<std::string> read_strings( std::istream& stm )
{
std::vector<std::string> strings ;
std::string str ;
while( read_string( stm, str ) ) strings.push_back( std::move(str) ) ;
return strings ;
}
int main()
{
const std::vector<std::string> strings =
{
"I\0 want\0 to\0 encrypt\0 a\0 exe(executable\0 file).",
"",
"I\0 am\0 reading\0 the\0 file\0 as\0 binary\0 but\0 when\0 i\0 Store\0 the\0 data\0 in\0 string",
"",
"\0\0\0\0",
"it\0 skips\0 the\0 null\0 values\0 and\0 the\0 end\0 result\0 after\0 decrypting\0 is\0 not\0 same."
};
const std::string file_name = "test_file.dat" ;
{
std::ofstream test_file( file_name, std::ios::binary ) ;
write_strings( test_file, strings ) ;
}
{
std::ifstream test_file( file_name, std::ios::binary ) ;
std::cout << ( strings == read_strings(test_file) ? "ok\n" : "failed\n" ) ;
}
}
|