I'm doing my first serialization programs with C++ using the friend keyword and operator overloading (>> <<).
The file in which I store the serialized objects is something called file.CARS, for storing car objects of course.
I created it this way :
std::ofstream output(file.CARS, std::ios::binary);
The file is created and I can store there my objects with no problem. Whoe开发者_StackOverflowver I discovered something:
The file is called file.CARS and I thought that the ios::binary and "unknown" extension (*.CARS) will help me prevent it from being opened with a simple text editor.
I was wrong... and the content can be seen and modified by a simple text editor...
Is there a way I can "protect" this file?
Thanks a lot for your help.
Not using standard C++. The binary
flag simply says how line-endings are handled. And all files are in binary format - that's what computers are all about! You probably want to read up on encryption.
If you're storing ASCII strings, then converting to binary doesn't really do anything ... the ASCII strings are already stored as binary data, i.e., "hello world", in actual memory is stored as (in hex):
0x68 0x65 0x6c 0x6c 0x6f 0x20 0x77 0x6f 0x72 0x6c 0x64
When you write those memory bytes to disk, whether it's an ASCII mode, or binary mode, you're going to end up with the same string stored in the memory of the disk. So any simple text editor that is going to read that memory off the disk and re-interpret the bytes, will just print-out the ASCII string that you saved.
If you don't want to have someone open your file and read your ASCII strings, then you're going to have to scramble them somehow. If encryption is too heavy-handed, you can do something simple like swapping the sign-bit (for an ASCII char
, which is signed), offsetting the values by a certain amount (watch out for wrap-around), do some light-weight run-length-encoding compression, etc. Just make sure when you read the values back, you properly reverse whatever transform you originally applied to the data.
Check out the answer to the question How do you serialize an object in C++? If you're just trying to obfuscate your data, boost::archive::binary_oarchive
will probably do the trick.
精彩评论