【发布时间】:2012-01-11 00:55:39
【问题描述】:
在尝试修改我的逻辑以响应this 问题。我决定使用message-size + protobuf-object-after-SerializeToArray 对序列化协议缓冲区对象,(如果您不明白我在说什么,请不要担心)。无论如何我的实现不起作用。所以我决定看看 c++ fstream 是如何工作的。这是一场语义噩梦,我不确定是否需要在每次读取后(甚至可能在每次写入后)使用seekg 重新定位位置句柄。我只使用 write() 和 get() 方法。以下人为的程序失败了,为什么失败了,在这种情况下我需要 seekg 吗?
#include <fstream>
#include <boost/cstdint.hpp>
#include <iostream>
void write()
{
boost::uint8_t one = (boost::uint32_t )255;
boost::uint8_t two = (boost::uint32_t) 254;
boost::uint8_t three =(boost::uint32_t) 253;
std::fstream file("test", std::fstream::out | std::fstream::binary | std::fstream::trunc);
file.write( (char *) &one, sizeof(one));
file.write( (char *) &two, sizeof(two));
file.write( (char *) &three, sizeof(two));
std::cout << file.tellg() << std::endl;
file.flush();
file.close();
}
void read()
{
boost::uint8_t one=0;
boost::uint8_t two=0;
boost::uint8_t three=0;
std::fstream file("test", std::fstream::in | std::fstream::binary);
file.get((char *) & one, sizeof(one));
file.get((char *) & two, sizeof(two));
file.get((char *) & three, sizeof(three));
std::cout << file.tellg() << std::endl;
std::cout << (boost::uint32_t) one << ":" << (boost::uint32_t) two << ":" << (boost::uint32_t)three<< std::endl;
file.close();
}
int main()
{
write();
read();
}
输出是:
3
-1
0:0:0
C++ 二进制文件 io 让我感到悲伤和愚蠢:(
【问题讨论】:
-
boost::uint8_t是unsigned char。要在std::cout上输出值,您应该将其转换为int(或任何其他非字符整数类型)。 -
是的,我也想通了,谢谢,更新了问题。
-
Hexdumping 结果文件给了我
feff 00fd(请记住字节序:),所以至少写作部分似乎正在工作。 -
使用调试器而不是依赖
cout,并在read代码中的所有用法之后检查fstream状态。 -
@steve 调试器的原因是内存中的东西,而不是文件中的东西,或者库的逻辑使用问题? :D
标签: c++ stl io binary-data