我正在尝试从磁盘读取文件,并输出其十六进制表示.
我使用的代码是:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file ("mestxt", ios::binary);
if (file.is_open())
{
char* buffer;
buffer= new char[0];
cout<< "File open"<<endl;
int count=0;
while (file.good())
{
file.read(buffer, 1);
cout<<hex<<int(*buffer)<<" ";
count++;
if (count%16==0) cout<<endl;
}
file.close();
}
}
Run Code Online (Sandbox Code Playgroud)
它有效,但它只是......让我感到恐惧,我不禁认为必须存在一些功能,这些功能可以做我做过的事情,只是更好.
输入:
bn0y5328w9gprjvn87350pryjgfpxl
输出:
文件打开
62 6e 30 79 35 33 32 38 77 39 67 70 72 6a 76 6e
38 37 33 35 30 70 72 79 6a 67 66 70 78 6c 6c
有一种简单的方法可以做到这一点.让STL负责设置一个循环.如果您只关心输出十六进制代码,这里是最简单的版本:
#include <iterator>
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream is("content", ios::binary);
cout << hex;
copy(
istream_iterator<char>(is),
istream_iterator<char>(),
ostream_iterator<int>(cout, " ")
);
}
Run Code Online (Sandbox Code Playgroud)
如果您还想计算字符数并进行格式化,则应将其更改为以下内容:
#include <iterator>
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int cnt = 0; // Will hold the number of characters
ifstream is("content", ios::binary);
cout << hex;
transform(
istream_iterator<char>(is),
istream_iterator<char>(),
ostream_iterator<int>(cout, " "), [&cnt] (char c) -> int {
if (cnt % 16 == 0) cout << endl;
cnt++;
return c;
}
);
}
Run Code Online (Sandbox Code Playgroud)
以上是使用lambda函数,因此它需要C++ 11.但是,您可以使用C++ 98中的自定义函子轻松实现相同的功能.
| 归档时间: |
|
| 查看次数: |
2236 次 |
| 最近记录: |