【问题标题】:can't write correctly large unsigned ints to binary file - c++无法将大的无符号整数正确写入二进制文件 - C++
【发布时间】:2016-04-13 23:51:10
【问题描述】:

在我的项目中,我需要写入一个二进制文件顺序无符号整数,重要的是每个数字需要精确的 4 个字节。 但是当我用十六进制编辑器打开二进制文件时,我看到了这种奇怪的情况: 数字写得正确,直到数字 9;在数字 10 之前,他将添加另一个额外的字节并写入“13”(并且已经弄乱了我的文件)。 奇怪的事情不断发生——从第 30 号开始,将写不同的字符,每个数字旁边都有一个。 这是为什么?如何解决,至少是尺寸问题? 这是我的简单示例代码:

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out);
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();

    return 0;
}

并附上我在文件中看到的图像: file capture on hex editor

谢谢

【问题讨论】:

  • 在全局命名空间中定义 void main() 在标准 C++ 中是非法的。你应该使用标准的int main()
  • 正确。我会改正的;

标签: c++ size binaryfiles unsigned-integer


【解决方案1】:

数字10是换行符LF,由于文件是以文本模式打开,所以转换为CRLF。

以二进制方式打开文件,处理二进制文件。

#include <iostream>
#include <fstream>
#include <string>

using std::string;
using std::cin;
using std::fstream;
using std::ios;

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out | ios::binary); // add OR with ios::binary
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();
}

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2019-02-23
    • 2015-02-15
    • 1970-01-01
    相关资源
    最近更新 更多