用于在二进制文件中搜索字符串的代码 [英] Code for searching for a string in a binary file

查看:462
本文介绍了用于在二进制文件中搜索字符串的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几天前问过这个问题:

I have asked this question a few days ago:

如何在二进制文件中查找ANSI字符串?

我有一个非常好的答案,后来变成了一个更难的问题:

and I got a really nice answer, what later turned into a much harder question: Can input iterators be used where forward iterators are expected? what is now really not on a level what I could understand.

我仍然在学习C ++我正在寻找一个简单的方法来搜索二进制文件中的字符串。

I am still learning C++ and I am looking for an easy way to search for a string in a binary file.

有人可以告诉我一个简单的C ++控制台程序的代码在二进制文件中查找字符串并将位置输出到stdout?

Could someone show me a simple code for a minimalistic C++ console program which looks for a string in a binary file and outputs the locations to stdout?

可能,你能告诉我


  1. 文件正在复制到内存的版本(假设二进制文件很小)

  1. a version where the file is being copied to memory (supposing the binary file is small)

另一个使用正确方式的链接问题

对不起,如果它听起来像我要求的人的代码,但我只是学习C + +,我想,也许其他人可以从这个问题,如果有人可以发布一些高质量的代码,什么是好的学习。 / p>

Sorry if it sounds like I'm asking for someone's code, but I am just learning C++ and I think maybe others could benefit from this question if someone could post some high quality code what is nice to learn from.

推荐答案

您的需求规范不清楚,例如 - 12112出现在12121字符(之后搜索继续在第4),还是在第3?

Your requirement specification is unclear, for example - where does "121" appear in "12121"... just at the first character (after which searching continues at the 4th), or at the 3rd as well? The code below uses the former approach.

#include <iostream>
#include <fstream>
#include <string>
#include <string.h>

int main(int argc, const char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " filename search_term\n"
            "Prints offsets where search_term is found in file.\n";
        return 1;
    }

    const char* filename = argv[1];
    const char* search_term = argv[2];
    size_t search_term_size = strlen(search_term);

    std::ifstream file(filename, std::ios::binary);
    if (file)
    {
        file.seekg(0, std::ios::end);
        size_t file_size = file.tellg();
        file.seekg(0, std::ios::beg);
        std::string file_content;
        file_content.reserve(file_size);
        char buffer[16384];
        std::streamsize chars_read;

        while (file.read(buffer, sizeof buffer), chars_read = file.gcount())
            file_content.append(buffer, chars_read);

        if (file.eof())
        {
            for (std::string::size_type offset = 0, found_at;
                 file_size > offset &&
                 (found_at = file_content.find(search_term, offset)) !=
                                                            std::string::npos;
                 offset = found_at + search_term_size)
                std::cout << found_at << std::endl;
        }
    }
}

这篇关于用于在二进制文件中搜索字符串的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆