Search code examples
c++binaryfiles

Writing the binary file using wfstream


I want to write a struct data in a binary file using wfstram class.

Why The output file is empty?

The following is my code.

#include "stdafx.h"
#include <string>
#include <fstream>

using namespace std;

struct bin_data
{
    wstring ch;
    size_t id;
};

int main()
{

    wfstream   f(L"test_bin_file.txt", ios::out | ios::binary);
    bin_data *d = new bin_data;
    d->id = 100;
    d->ch = L"data100";
    f.write((wchar_t*)&d, sizeof(struct bin_data));
    f.close();

    return 0;
}

Solution

  • I don't like much working with wide streams when dealing with binary data - binary are ultimately bytes, so you don't have to worry about much about char vs wchar. Code below writes 30 bytes on x64 - 8 for id, 8 for length and 14 (7*2) for string itself

    int main() {
    ofstream  f(L"QQQ.txt", ios::out | ios::binary);
    
    bin_data *d = new bin_data;
    d->id = 100;
    d->ch = L"data100";
    
    // ID first
    f.write((char*)&d->id, sizeof(d->id));
    // then string length
    auto l = d->ch.length();
    f.write((char*)&l, sizeof(l));
    // string data
    f.write((char*)d->ch.data(), l*sizeof(wchar_t));
    
    f.close();
    
    return 0;
    }