【发布时间】:2011-11-22 09:41:16
【问题描述】:
如何读取二进制文件(我不知道它的类型或其中存储的内容)并将0s 和1s 打印到文本文件中?
#include <iostream>
#include <fstream>
#include <string.h>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
char ch;
bool x;
int i = 0;
if (argc < 3)
{
cout << endl << "Please put in all parameters" << endl;
return 0;
}
char *c = new char[4];
ifstream fin(argv[1], ios_base::in | ios_base::binary);
if (!fin.is_open())
{
cout << "Error opening input file" << endl;
return 0;
}
if (!strcmp(argv[2], "-file"))
{
ofstream fout(argv[3]);
if (!fout.is_open())
{
cout << "Error opening output file" << endl;
return 0;
}
while (fin.read(c, sizeof ch))
{
fout << c;
}
cout << "Contents written to file successfully" << endl;
fout.close();
}
else if (!strcmp(argv[2], "-screen"))
{
cout << endl << "Contents of the file: " << endl;
while (fin.read((char *)&x,sizeof x))
{
cout << x;
}
cout << endl;
}
else
{
cout << endl << "Please input correct option" << endl;
return 0;
}
fin.close();
return 0;
}
【问题讨论】:
-
这是作业吗?如果没有,而您只想查看内容,您可以在十六进制编辑器中打开文件进行查看。
-
是的 - 你试过了吗?如果是这样,为什么不发布您的代码并告诉我们什么不起作用。
-
是的,这是作业......我会发布代码......
-
@MMavipc,我把代码贴出来了......