C++ 将ASCII文件转换为C++;

C++ 将ASCII文件转换为C++;,c++,C++,首先,我想说的是,我是在互联网上搜索了很多次之后才来发布我的问题的,没有找到一篇合适的文章或解决方案 正如标题中提到的,我需要将ASCII文件转换为二进制文件 我的文件由行组成,每行包含由空格分隔的浮点 我发现很多人使用C++,因为这样的任务比较容易。 我尝试了以下代码,但生成的文件太大了 #include <iostream> #include <fstream> #include <string> using namespace std; int m

首先,我想说的是,我是在互联网上搜索了很多次之后才来发布我的问题的,没有找到一篇合适的文章或解决方案

正如标题中提到的,我需要将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;
}

感谢您抽出时间

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

#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;
}
#包括
#包括
int main()
{
浮动值=0.0;
std::ifstream输入(“my_input_file.txt”);
std::流输出(“output.bin”);
while(输入>>值)
{
write(static_cast(&value),sizeof(value));
}
input.close();//显式关闭文件。
output.close();
返回退出成功;
}
在上面的代码片段中,使用格式化读入变量来读取
浮点值

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

重复读写操作,直到没有更多的输入数据

读者练习/OP:
1.打开文件时的错误处理。

2.优化读写(使用更大的数据块进行读写)

你想用什么格式?二进制格式几乎可以表示任何内容。如果您的行包含三个
float
为什么要将它们读入
int
变量?请提供一个,包括输入文件、预期输出文件大小和实际输出文件大小。虽然我能猜出你在这种情况下的问题是什么,但这应该包括在每个问题中。顺便说一句,你的代码有什么问题吗?嗨,托马斯,谢谢你,我尝试了你的代码,但出现了一个错误:错误:无效的静态转换,从类型“float*”转换为类型“char*”输出。write(静态转换(&value),sizeof(value))@米高梅:它(仍然)需要是一个
重新解释\u cast
@MGM您也可以先将其转换为
void*
,然后转换为
char*
静态\u cast(静态\u cast(&value))
将起作用。“指针指向void(可能是cv限定的)类型的prvalue可以转换为指向任何对象类型的指针。”(请参阅)您也可以使用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
#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;
}