fstream二进制读/写行为

时间:2012-12-24 02:10:12

标签: c++ fstream binary-data

我在写/读二进制值时遇到了“奇怪”的问题:

bool readHeader(std::fstream &file)
{
    file.seekg(0);
    int a = file.tellg();
    file.get(reinterpret_cast<char*>(&a), sizeof(a));
    int b = file.tellg();
    file.get(reinterpret_cast<char*>(&b), sizeof(b));
    int c = file.tellg();
    file.seekg(32);
    return !(file.bad());
}

bool writeHeader(std::fstream &file)
{
    file.seekg(0);
    int a = file.tellg();
    file.write(reinterpret_cast<char*>(&a), sizeof(a));
    int b = file.tellg();
    file.write(reinterpret_cast<char*>(&b), sizeof(b));
    int c = file.tellg();
    file.seekg(32);
    return !(file.bad());
}

其中'a'是uint32_t而'b'是uint64_t。

这里有什么奇怪的 - 变量a,b和c具有以下值:

readHeader中的

:0,3,10

在writeHeader中:0,4,12

这个原因,我必须做一个:

file.seekg(1, std::ios_base::cur);

每次获取操作后。这是对的吗?我做错了吗?

1 个答案:

答案 0 :(得分:1)

使用read()

get()将最多n-1个字符或\ n的EOF或错误(以1为准)提取到C样式字符串

读取最多n个字符或EOF(以1为准)到任何内存位置。

相关问题