在C ++中转换文本文件和二进制文件

时间:2013-12-23 13:16:27

标签: c++

为了将普通文本文件转换为二进制文件,然后将该二进制文件转换回文本文件,以便第一个文本文件与最后一个文本文件相等,我编写了下面的代码。 但 bintex 文本文件和 final 文本文件不相等。我不知道哪部分代码不正确。 输入样本(“bintex”)包含: 1983 1362 结果(“最终”)包含: 959788084 这当然不相等。

#include <iostream>
#include <fstream>
using namespace std;

int main() try
{
    string name1 = "bintex", name2 = "texbin", name3 = "final";

     ifstream ifs1(name1.c_str());
     if(!ifs1) error("Can't open file for reading.");

     vector<int>v1, v2;
     int i;
     while(ifs1.read(as_bytes(i), sizeof(int)));
     v1.push_back(i);
     ifs1.close();

     ofstream ofs1(name2.c_str(), ios::binary);
     if(!ofs1) error("Can't open file for writting.");
     for(int i=0; i<v1.size(); i++)
         ofs1 << v1[i];
         ofs1.close();

     ifstream ifs2(name2.c_str(), ios::binary);
      if(!ifs2) error("Can't open file for reading.");

         while(ifs2.read(as_bytes(i), sizeof(int)));
          v2.push_back(i);
          ifs2.close();

     ofstream ofs2(name3.c_str());
     if(!ofs2) error("Can't open file for writting.");
     for(int i=0; i<v2.size(); i++)
         ofs2 << v2[i];
         ofs2.close();

        keep_window_open();
        return 0;
}

//********************************

catch(exception& e) 
{
    cerr << e.what() << endl;
    keep_window_open();
    return 0;
}

3 个答案:

答案 0 :(得分:1)

这是什么?

 while(ifs1.read(as_bytes(i), sizeof(int)));

它看起来像一个循环,读取所有输入并将其抛弃。之后的行表明你应该使用大括号而不是分号,并在块中进行写入。

答案 1 :(得分:0)

您的读写操作不对称。

ifs1.read(as_bytes(i), sizeof(int))

抓取4个字节,并将值转储到传递的char *中。

ofs1 << v1[i];

输出v [i]中的整数作为文本。这些是非常不同的格式。 如果您使用>>阅读,那么您将获得更多成功。

要说明,第一次读取可能看起来像这个{'1','9','8','3'},我猜这将是你在将它打到int时看到的959788084。你的第二次阅读将是{' ','1','3','6'},而不是你所希望的那样。

答案 2 :(得分:0)

目前尚不清楚(对我来说,至少),你想要做什么。 当你说原始文件包含1983 1262时,做什么 你的意思是?它包含两个四字节整数 一些未指定的格式,其值为1983和1262?如果是这样, 问题可能是由于您的机器没有使用相同的 格式。通常,您不能只读取字节(使用 istream::read)并期望它们代表你的任何东西 机器的内部格式。你必须读入字节 缓冲区,并根据其格式取消格式化 他们写的。

当然,以二进制模式打开流意味着 实际数据采用二进制格式;它只是影响 如何(或更严格地说,是否)行的事情 结尾被编码,以及如何识别文件结尾。 (严格来说,二进制文件不分为行。它 只是一个字节序列。当然,其中一些字节 可能具有您在程序中解释和新的值 行字符。)如果您的文件实际包含九个字节 字符对应于"1983 1362", then you'll have to parse them as a text format, even if the file is written in binary. You can do this by reading the entire file into a string, and using std :: istringstream ; _or_, on most common systems (but not necessarily on all exotics) by using&gt;&gt;`to 读取,就像使用文本文件一样。

编辑:

只是一个简单的提醒:您没有显示as_bytes的代码, 但我愿意猜测有一个reinterpret_cast 它。任何时候你必须使用重新解释演员,你可以 非常肯定你正在做的事情不是便携式的,如果是的话 应该是便携式的,你做错了。

相关问题