gpt4 book ai didi

c++11 - 如何将二进制数据写入现代 C++ 中的文件?

转载 作者:行者123 更新时间:2023-12-01 10:43:15 25 4
gpt4 key购买 nike

在 C 中将二进制数据写入文件很简单:使用 fwrite,传递要写入的对象的地址和对象的大小。现代 C++ 是否有更“正确”的东西,或者我应该坚持使用 FILE* 对象?据我所知,IOStream 库用于写入格式化数据而不是二进制数据,写入成员要求一个 char*,这让我的代码中充满了强制转换。

最佳答案

所以这里的游戏是在读取和写入时启用参数依赖查找,并确保您不要尝试读取/写入非平面数据的内容。

它无法捕获包含指针的数据,也不应该以这种方式读取/写入,但总比没有好

namespace serialize {
namespace details {
template<class T>
bool write( std::streambuf& buf, const T& val ) {
static_assert( std::is_standard_layout<T>{}, "data is not standard layout" );
auto bytes = sizeof(T);
return buf.sputn(reinterpret_cast<const char*>(&val), bytes) == bytes;
}
template<class T>
bool read( std::streambuf& buf, T& val ) {
static_assert( std::is_standard_layout<T>{}, "data is not standard layout" );
auto bytes = sizeof(T);
return buf.sgetn(reinterpret_cast<char*>(&val), bytes) == bytes;
}
}
template<class T>
bool read( std::streambuf& buf, T& val ) {
using details::read; // enable ADL
return read(buf, val);
}
template<class T>
bool write( std::streambuf& buf, T const& val ) {
using details::write; // enable ADL
return write(buf, val);
}
}

namespace baz {
// plain old data:
struct foo {int x;};
// not standard layout:
struct bar {
bar():x(3) {}
operator int()const{return x;}
void setx(int s){x=s;}
int y = 1;
private:
int x;
};
// adl based read/write overloads:
bool write( std::streambuf& buf, bar const& b ) {
bool worked = serialize::write( buf, (int)b );
worked = serialize::write( buf, b.y ) && worked;
return worked;
}
bool read( std::streambuf& buf, bar& b ) {
int x;
bool worked = serialize::read( buf, x );
if (worked) b.setx(x);
worked = serialize::read( buf, b.y ) && worked;
return worked;
}
}

我希望你明白这一点。

live example .

可能你应该限制所述基于 is_pod 而不是标准布局的写作,如果在构建/销毁时发生特殊情况,也许你不应该二进制 blitting 类型。

p>

关于c++11 - 如何将二进制数据写入现代 C++ 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28745383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com