C++ 文件 (exe) 读取自身

C++ file (exe) reading itself

我想让我的二进制文件自行读取,但我遇到了一些麻烦。现在这就是我得到的:

#include <iostream>
#include <fstream>

int main(int argc, char * argv[])
{
    char data[1000];
    std::fstream file(argv[0], std::ios::in | std::ios::binary);
    file >> data;

    std::cout << data;

    system("PAUSE");
    return 0;
}

这只打印前 3 个字符,出于某种原因...就是这样。我不知道为什么它不读取整个文件。有帮助吗?

您需要读取未格式化的可执行文件,并将其作为二进制文件打开。使用好旧的恐惧; filebuf 表面上很吸引人,但它仍然会调用您不想要的语言环境转换。

文件中的某些值导致流输入过早结束,例如\n

试试

int main(int argc, char * argv[])
{
    char data[1000];
    std::ifstream file(argv[0], std::ios::in | std::ios::binary);
    int i = 0; 
    while (file.get(data[i])
    {
       i++;
       if (i == 1000) break;
    }

    for (int j = 0; j < i; j++)
        std::cout << std::hex << data[j];

    system("PAUSE");
    return 0;
}

编辑:根据 OP

的评论更新

在 C++ 中,您应该避免使用 C 风格的数组。请改用向量。矢量具有动态大小,可以在需要时增长。

int main(int argc, char * argv[])
{
    char c;
    vector<char> data;
    std::ifstream file(argv[0], std::ios::in | std::ios::binary);
    while (file.get(c)
    {
       data.push_back(c);
    }

    for (auto t : data)  // for each ...
    {
        std::cout << std::hex << t;
    }

    system("PAUSE");
    return 0;
}

C++ operator >> (const char *) 流函数仅适用于 C 风格的字符串。它不适用于任意二进制数据。您需要决定您希望输出的样子,并编写代码以您想要的格式输出原始的、任意的二进制数据。

您还需要继续阅读。并且您需要使用不会溢出缓冲区的读取函数。