【问题标题】:Convert ASCII file to Binary format in C++在 C++ 中将 ASCII 文件转换为二进制格式
【发布时间】:2018-04-09 22:17:04
【问题描述】:

首先,我想表达我在网上搜索了很多之后,没有找到合适的文章或解决方案来发布我的问题。

如标题所述,我需要将 ASCII 文件转换为二进制文件。

我的文件由行组成,每一行都包含用空格分隔的浮点数。

我发现很多人使用 c++,因为这种任务更容易。

我试过下面的代码,但是生成的文件太大了。

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

using namespace std;


int main(int argc, char const *argv[])
{
   char buffer;

    ifstream in("Points_in.txt");
    ofstream out("binary_out.bin", ios::out|ios::binary);

    float nums[9];

    while (!in.eof())
    {
        in >> nums[0] >> nums[1] >> nums[2]>> nums[3] >> nums[4] >> nums[5]>> nums[6] >> nums[7] >> nums[8];

        out.write(reinterpret_cast<const char*>(nums), 9*sizeof(float));

    }
    return 0;
}

我找到了这两个资源:

http://www.eecs.umich.edu/courses/eecs380/HANDOUTS/cppBinaryFileIO-2.html https://r3dux.org/2013/12/how-to-read-and-write-ascii-and-binary-files-in-c/

如果您还有其他资源,我不胜感激?

我的 ASCII 输入文件中的行如下:

-16.505 -50.3401 -194 -16.505 -50.8766 -193.5 -17.0415 -50.3401 -193.5

感谢您的宝贵时间

【问题讨论】:

  • 你想到的格式是什么?二进制格式几乎意味着任何东西。
  • 如果您的行包含三个float,为什么要将它们读入int 变量?
  • 请提供minimal reproducible example,包括输入文件、您预期的输出文件大小和实际输出文件大小。虽然我可以猜到你在这种情况下的问题是什么,但这应该包含在每个问题中。
  • 那么你的代码有什么问题?

标签: c++


【解决方案1】:

这里有一个更简单的方法:

#include <iostream>
#include <fstream>

int main()
{
  float value = 0.0;
  std::ifstream input("my_input_file.txt");
  std::ofstream output("output.bin");
  while (input >> value)
  {
    output.write(static_cast<char *>(&value), sizeof(value));
  }
  input.close(); // explicitly close the file.
  output.close();
  return EXIT_SUCCESS;
}

在上面的代码片段中,float 是使用格式化读取到变量中的。

接下来,数字以原始二进制形式输出。

重复读写直到没有更多的输入数据。

读者练习/OP:
1. 打开文件的错误处理。
2.优化读写(使用更大的数据块进行读写)。

【讨论】:

  • 嗨,Thomas 谢谢我尝试了您的代码,但出现了错误:错误:从类型“float*”到类型“char*”的无效静态转换输出.write(static_cast(&value) , sizeof(value));
  • @MGM:它(仍然)需要是reinterpret_cast
  • @MGM 您也可以先转换为void *,然后再转换为char *static_cast&lt;char *&gt;(static_cast&lt;void *&gt;(&amp;value)) 即可。 “指向 void(可能是 cv 限定)的类型指针的纯右值可以转换为指向任何对象类型的指针。”(参见 cppreference
  • 你也可以使用 C 风格的演员表:(const char *)
  • @ThomasMatthews 我认为,它可以工作: output.write((const char *)(&value), sizeof(value));对于第一行:-16.505 -50.3401 -194 -16.505 -50.8766 -193.5 -17.0415 -50.3401 -193.5 我在第一个二进制输出文件中得到了这个:3d0a 84c1 435c 49c2 0000 42c3 3d0a 84c1
猜你喜欢
  • 2014-03-24
  • 2011-05-12
  • 2016-10-02
  • 2020-10-17
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
相关资源
最近更新 更多