【问题标题】:Can I do an Unformatted Write to a File Then a Formatted Read From a File for Integral Types?我可以先对文件进行未格式化的写入,然后再对文件进行格式化读取以获取整数类型吗?
【发布时间】:2016-06-17 20:15:57
【问题描述】:

鉴于我将整数的vector 写入未格式化的临时文件:

ofstream foo("foo.txt", ios::binary);
const auto length= size(output);

foo.write(reinterpret_cast<const char*>(length), sizeof(length));

if(!empty(input)) foo.write(reinterpret_cast<const char*>(data(output)), sizeof(decltype(output)::value_type) * length);

我可以稍后从inputoutput 相同类型的文件中执行以下格式化读取:

ifstream foo("foo.txt", ios::binary);
size_t size;

foo.read(reinterpret_cast<char*>(size), sizeof(size));
input.resize(size);

if(!empty(input)) copy(istream_iterator<decltype(output)::value_type>(foo), istream_iterator<decltype(output)::value_type>(), begin(input));

【问题讨论】:

    标签: c++ binaryfiles ifstream ofstream formatted


    【解决方案1】:

    我可以先对文件进行未格式化的写入,然后再从文件中读取整型文件的格式吗?

    不,你不能那样做。

    使用无格式写入写入数据的文件内容与有格式写入有很大不同。格式化的读取无法准确解释未格式化的数据。

    【讨论】:

    • char 怎么样?我只看到在那里进行格式化写入和未格式化读取的问题。
    • @LogicStuff, char 可以,只要您在执行格式化读取时不跳过空格。
    • @LogicStuff 你对char 的看法是对的,但我只是对这个令人尴尬的问题大发雷霆。
    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多