laughing
laughing

Reputation: 163

How to read string from a binary file in C++?

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.

Upvotes: 1

Views: 480

Answers (1)

Eugene
Eugene

Reputation: 7688

In your code,

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); //<--bug
    fout.close();
}

instead of the line marked with bug<--, you need

fout.write(ascII_text.data(), input_size);

Upvotes: 3

Related Questions