I have a function two functions, writing and reading from the binary file in C++.
void save_ascII(string ascII_text, string filename)
{
ofstream fout;
fout.open(filename,ofstream::binary);
size_t input_size = ascII_text.size();
if (fout.is_open())
{
fout.write(reinterpret_cast<char*>(&input_size), sizeof(input_size));
fout.write(reinterpret_cast<char*>(&input_size), input_size);
fout.close();
}
}
void read_ascII(string filename)
{
string read_input;
ifstream fin(filename,fstream::binary);
size_t read_size;
if (fin.is_open())
{
fin.read(reinterpret_cast<char*>(&read_size), sizeof(read_size));
read_input.resize(read_size);
fin.read(&read_input[0], read_size);
fin.close();
}
}
The problem is that when it reads from the binary, it just dummy data on the memory.
When it reads from the binary file, it shows:
►╠╠╠╠╠╠╠╠▄²A
Any suggestion really appreciates it.
main) in your question, and show an example of input file. BTW, in 2021, you should use UTF-8 everywhere. Notice that a good example of binary files are executables. On Linux e.g. Debian they use the ELF formatg++ -Wall -Wextra -gto get warnings and debug information, then use the GDB debugger to understand the behavior of your program. You need first to document (e.g. in English, perhaps using EBNF notation) the format of your input files.fstream::out|fstream::binaryandfstream::in|fstream::binaryshould be your defacto read masks. I noticed you never bothered to check that the read actually succeeded. Nor did you mention whether you examined the file via hex dump to ensure the content was really there. If you do, you'll notice you're writing the length twice and completely ignoring the actual string content on output. Cut+paste can be cruel sometimes, eh?