3

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;
}
5
  • If you expect you could save string content into a file, you're wrong. You'll get only pointer/counter saved Commented Jul 25, 2016 at 20:18
  • And you don't need &d, this is just crap Commented Jul 25, 2016 at 20:19
  • So how to write d? Commented Jul 25, 2016 at 20:32
  • Write id first, it is of fixed length, f.write((char*)&d->id, sizeof(size_t)); Then write string length, again fixed record and last content of the string using d->ch.data() Commented Jul 25, 2016 at 20:38
  • The purpose of existence for std::wfstream is to translate between Unicode code points, represented by wchar_t on the program side, and UTF-8, GB18030, or other kinds of narrow multibyte encoding, represented by chars, on the filesystem side. Giving it an ios::binary does not change that Commented Nov 9, 2017 at 20:18

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.