在C++中转换文本文件和二进制文件
Converting between text files and binary files in C++
为了将一个普通的文本文件转换为二进制文件,然后将该二进制文件转换回文本文件,使第一个文本文件与最后一个文本文件相等,我编写了以下代码。但是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 using
std::istringstream; _or_, on most common
systems (but not necessarily on all exotics) by using
>`to阅读,就像阅读文本文件一样。
编辑:
只是一个简单的提醒:您没有显示as_bytes
的代码,但我猜里面有一个reinterpret_cast
它。任何时候你必须使用重新诠释的演员阵容,你都可以非常确定你所做的是不可移植的,如果是本应是便携的,但你做得不对。
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作