0

我正在尝试从磁盘读取文件,并输出其十六进制表示。

我使用的代码是:

#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();
        }
}

它有效,但它只是......让我感到恐惧,我不禁认为必须存在一些功能可以完成我所做的事情,只是更好。

输入:

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

4

3 回答 3

6

有一种简单的方法可以做到这一点。只需让 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, " ")
       );
}

如果您还想计算字符数并进行格式化,则应将其更改为以下内容:

#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; 
            }
        );
}

以上是使用 lambda 函数,所以需要 C++11。但是,您可以使用 C++98 中的自定义函子轻松实现相同的目标。

于 2013-01-29T15:09:32.013 回答
2

除了易于修复未定义的行为(分配char[0]而不是char[1],然后写入buffer[0]- 超过已分配空间的一个字节)之外,您的程序还可以。您可以使用标量代替单元素数组。

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file ("mestxt", ios::binary);
    if (file.is_open())
    {
        char buffer;
        cout<< "File open"<<endl;
        int count=0;
        while (file.good())
        {
            file.read(&buffer, 1);
            cout<<hex<<int(buffer)<<" ";
            if ((++count)%16==0) cout<<endl;
        }
        file.close();
    }
}

您可以通过一次读取多个字符来提高程序的效率,但是对于小尺寸的输入,这根本不重要。

于 2013-01-29T14:56:41.140 回答
0

如果您知道您的文件将足够小以适合内存,那么将整个文件读入缓冲区然后解析它会更快

std::ifstream file("mestxt", std::ios_base::binary);
file.seekg(0, std::ios_base::end);
std::vector<char> buffer(file.tellg()); 
file.seekg(0, std::ios_base::beg);
file.read(&buffer.front(), buffer.size());

std::cout << std::hex;
std::copy(buffer.cbegin(), buffer.cend(), std::ostream_iterator<int>(std::cout, " "));
于 2013-01-29T15:17:26.080 回答