我想写个控制台程序,逐字节的读取png文件的内容,然后以16进制的形式输出出来,看看png文件里面写了些什么。
但是,总是读完前5个字节,就读到文件尾了。
我自己搞不懂为什么,身边也没有人可以问。希望有热心的好哥哥帮忙解答一下。谢谢~ q(≧▽≦q)
下面是我的代码
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
ifstream inFile1;
int main()
{
cout << "Please Enter the File's Name which You Want to Open.\n";
string fileName1;
cin >> fileName1;
inFile1.open(fileName1);
char ch;
int counter = 0;
int temp = 0;
inFile1.read(&ch, 1);
while (!inFile1.eof())
{
temp = ch & 0x000000ff;
cout <<hex<<temp<< "\t";
counter++;
if (counter == 5)
{
counter = 0;
cout << endl;
}
inFile1.read(&ch, 1);
}
if (inFile1.eof())
cout << "End of file reached.\n";
else if (inFile1.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
inFile1.close();
return 0;
}
我这里将fileName1变量的类型改为字符数组后,测试是正常运行的。
修改如下:
参考链接:
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
ifstream inFile1;
int main()
{
cout << "Please Enter the File's Name which You Want to Open.\n";
// string fileName1;
char fileName1[200];
cin >> fileName1;
// https://blog.csdn.net/sinat_36219858/article/details/80369255
inFile1.open(fileName1);
char ch;
int counter = 0;
int temp = 0;
inFile1.read(&ch, 1);
while (!inFile1.eof())
{
temp = ch & 0x000000ff;
cout <<hex<<temp<< "\t";
counter++;
if (counter == 5)
{
counter = 0;
cout << endl;
}
inFile1.read(&ch, 1);
}
if (inFile1.eof())
cout << "End of file reached.\n";
else if (inFile1.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
inFile1.close();
return 0;
}