【问题标题】:How to convert binary files context into int/long value in C++如何在 C++ 中将二进制文件上下文转换为 int/long 值
【发布时间】:2014-12-11 17:12:55
【问题描述】:

我正在使用 fstream 将值存储在二进制文件中。该值为无符号短类型。

unsigned shord value=1750; //2 byte variable
file.write((char*)&value,sizeof(value));

我的问题是我想在另一个函数中读取这个二进制文件,但它给了我一些奇怪的符号(显然是因为它是二进制的)。
有什么方法可以获取这两个字节并将它们转换为我的旧值(1750)?

这是我尝试过的:

cout <<(unsigned short)(unsigned char)(s2[8]);//s2 variable where the whole body is stored
cout <<(unsigned short)(char*)(s2[8]);

我也尝试过其他的东西,但它们只是小菜一碟,不值得在这里介绍。

【问题讨论】:

  • 您是否相应地使用file.read((char*)&amp;value,sizeof(value)); 读取这些值?
  • 不要在 C++ 中使用 C 风格的强制转换。
  • 你到底是什么意思?嘿 παντα ρει 我也是希腊人。你能给我一个私人邮件联系你吗?
  • @Donisis 我的意思是不要做这样的演员表:(char*)&amp;value 在 C++ 中。正确的 C++ 演员表是 reinterpret_cast&lt;char*&gt;(&amp;value)。 C++ 有许多不同的转换操作,C 风格的转换可能意味着其中任何一个,如果它使用与您预期不同的转换类型,可能会产生灾难性的后果。
  • @NelsonTeixeira 我怀疑问题是由字节序引起的,除非文件是在不同的机器上生成的,具有不同的架构。

标签: c++ binary fstream ifstream ofstream


【解决方案1】:

您可以这样做(注意使用 C++11 功能):

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

void write_shorts(string filename, vector<unsigned short> shorts)
{
    ofstream f;

    f.open(filename, ofstream::trunc|ofstream::binary);

    for(auto s: shorts)
        f.write(reinterpret_cast<char*>(&s), sizeof(s));
}

auto read_shorts(string filename)
{
    ifstream f(filename);
    vector<unsigned short> res;
    short x;

    while(f.read(reinterpret_cast<char*>(&x), sizeof(x)))
        res.push_back(x);

    return res;
}

int main()
{
    // Write 3 shorts to a file
    write_shorts("myshorts", {4711, 1, 0xffff});

    // Read them back into a vector
    auto v = read_shorts("myshorts");

    cout << "Read " << v.size() << "shorts: " << endl;

    for(auto x: v)
        cout << x << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2019-02-28
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多