Record an experience of debugging.
Here are two ways to read string and store it in std::string.
One will have ‘\x00’ in std::string object, the other has not.
#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>
using namespace std;
std::string filePath = "txt";
void WriteData()
{
ofstream output;
output.open( filePath.c_str(), ios::binary );
if( output.is_open() == false )
{
cout << "open failed: " << filePath.c_str() << endl;
return;
}
std::string str = "TX1";
output.write( str.c_str(), str.size()+1);
output.close();
cout << "finished\n";
}
std::string cppStr;
void ReadData() {
ifstream input;
input.open(filePath.c_str(), ios::binary); // default way
if (input.is_open() == false)
{
cout << "open failed: " << filePath << endl;
return;
}
// std::string str;
// str.resize(4);
// str.reserve(4);
// input.read( (char*)str.c_str(), 4 ); // append `\x00` for std::string
char __str[10];
input.read( __str, 4 );
cppStr = __str; // std::string will remove `\x00`
std::cout << "read str: " << cppStr << std::endl;
input.close();
}
int main()
{
WriteData();
ReadData();
std::cout << "cppStr: " << cppStr << std::endl;
if( cppStr.back() == '\x00' )
{
std::cout << "this is a null binary string.\n";
}
return 0;
}