我试着理解std::basic_ofstream。我从这个开始:
#include <fstream>
int main() {
std::ofstream test_stream("data.txt");
int my_int = 12;
double my_double = 26.8;
test_stream << my_int << " " << my_double;
}在记事本中打开data.txt时,可以看到
12 26.8这告诉我,<<格式化了输出,并将输出存储为chars (优先选择)。实际上,data.txt的大小是7个字节。
我希望将数据输出为原始位,以防止转换为字符串。我发现我可以用write
test_stream.write((char*) & my_int, 4);
test_stream.write((char*) & my_double, 8);从功能上讲,它能实现我想要的/预期的效果。data.txt将显示为12个字节,它是12和26.8的二进制表示形式。然而,我希望得到一些更好的表示法。我尝试了put成员函数,但是只输出了int的一个字节。
然后我考虑了将basic_ofstream的角色类型改为int的可能性,我希望我能这样做。
int main() {
std::basic_ofstream<int> test_stream("data.txt");
int my_int = 123412431;
test_stream.put(my_int);
}或者这个
int main() {
std::basic_ofstream<int> test_stream("data.txt");
int my_int = 123412431;
test_stream << my_int;
}第一个只给出一个字节的输出Ï。第二个给出了一个错误。我认为std::basic_ofstream<int>的目的是使put过载以传输int。
问题
那么,std::basic_ofstream<int>和std::basic_ofstream<char>有什么区别呢?有没有办法让std::basic_ofstream<int>做我想做的事?(为了清楚起见:我想要的是write示例与put或<<的功能。)
发布于 2022-08-05 02:33:11
int不是字符类型。不能将其用作std::basic_ostream的模板参数。
(从技术上讲,它可能被支持为实现定义的字符类型,但我认为没有任何实现能够做到这一点。)
通常只支持char (对应于std::ostream)和wchar_t (对应于std::wostream)。
您使用std::ofstream输出对象表示的方法是正确的,应该如何实现,只是您应该使用reinterpret_cast<const char*>而不是(char*),并且应该使用sizeof(/*variable name*/)而不是神奇的数字。这两种方法都有助于避免错误。
您可以将其包装在一个函数中,以获得更好的表示法,这不需要重复变量名两次:
template<typename T>
std::ostream& print_object_representation(std::ostream& o, const T& t) {
// Use `std::addressof(t)` instead of `&t` to
// correctly handle classes with overloaded `operator&`
o.write(reinterpret_cast<const char*>(&t), sizeof(t));
return o;
}
//...
print_object_representation(test_stream, my_double);https://stackoverflow.com/questions/73243968
复制相似问题