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

Converting between text files and binary files in C++

本文关键字:文件 二进制文件 文本 转换 C++      更新时间:2023-10-16

为了将一个普通的文本文件转换为二进制文件,然后将该二进制文件转换回文本文件,使第一个文本文件与最后一个文本文件相等,我编写了以下代码。但是bintex文本文件和final983 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;
}

这是什么?

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

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

您的读写操作不是对称的。

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

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

ofs1 << v1[i];

将v[i]中的整数作为文本输出。这些是非常非常不同的格式。如果你用>>阅读,你会取得更大的成功。

为了说明,第一次阅读可能看起来像{'1','9','8','3'},我想当你把它双关成int时,它会是你看到的959788084。你的第二次阅读可能是{' ','1','3','6'},这也不是你所希望的。

(至少对我来说)你想做什么还不清楚。当你说原始文件包含1983 1262时,该怎么办你真的是说?它包含两个四字节整数,在一些未指定的格式,其值为1983和1262?如果是,问题可能是由于您的机器没有使用相同的总体安排通常,您不能只读取字节(使用istream::read),并期望它们在您的机器的内部格式。你必须将字节读入一个缓冲区,并根据它们是书面的。

当然,以二进制模式打开流并不意味着实际数据是一些二进制格式;它只是影响比如how(或者更严格地说,是否)line对结尾进行编码,以及如何识别文件结尾。(严格来说,二进制文件不分行只是一个字节序列。当然,其中一些字节可能具有您在程序中解释和新的值行字符。)如果您的文件实际上包含9个字节字符对应于"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 usingstd::istringstream; _or_, on most common systems (but not necessarily on all exotics) by using>`to阅读,就像阅读文本文件一样。

编辑:

只是一个简单的提醒:您没有显示as_bytes的代码,但我猜里面有一个reinterpret_cast它。任何时候你必须使用重新诠释的演员阵容,你都可以非常确定你所做的是不可移植的,如果是本应是便携的,但你做得不对。