Code for finding a string in a binary file

I asked this question a few days ago:

How to find ANSI string in binary?

and I got a really good answer , which later turned into a more complex question: Can I use input iterators, where are the iterators waiting for transitions? that now is really not at the level that I could understand.

I'm still learning C ++, and I'm looking for an easy way to find a string in a binary.

Can someone show me simple code for a minimalist C ++ console program that looks for a string in a binary file and prints data to stdout?

Maybe you can show me

  • the version in which the file is copied to memory (suppose the binary is small)

  • and another that uses the correct method from related questions

Sorry if this sounds like I'm asking someone for code, but I'm just learning C ++, and I think that maybe others could take advantage of this question if someone could post some kind of high-quality code from which it’s nice to learn.

0
c ++ iterator boost search binaryfiles
source share
2 answers

Your specification of requirements is unclear, for example - where "121" appears in "12121" ... only the first character (after which the search continues on the 4th) or on the third? The code below uses the first 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; } } } 
+2
source share

This is one way to do part 1. I'm not sure that I would describe it as high quality, but perhaps on the side of minimalism.

 #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char *argv[]) { std::ifstream ifs(argv[1], ios::binary); std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); size_t pos = str.find(argv[2]); if (pos != string::npos) cout << "string found at position: " << int(pos) << endl; else cout << "could not find string" << endl; return 0; } 
+1
source share

All Articles