0

I think that's not a difficult question but i want to know how to do it in a C++ way. I want to search the position of a defined word or sequence.

I read this post stack similar question and the answer looks great. But i don't know how to apply this solution with a file. This std instruction it's easy to apply in a or a but i don't know how to apply to a file and a sequence.

Instruction:

std::ifstream file; std::search(std::istreambuf_iterator<char>(file.rdbuf()) // search from here , std::istreambuf_iterator<char>() // ... to here , pSignature // looking for a sequence starting with this , pSignature+sigSize); // and ending with this 

Can I use a string to store the sequence to search in the file ???

Could someone post an easy example of how to apply the search instruction, i always obatin and big error when I compile it.

I don't use windows and don't want to use Boost library.

Thanks in advance.

1 Answer 1

4

Read the file into a string (assuming it's not huge). You can then use string::find or std::algorithm.

using namespace std; // read entire file into a string ifstream file(".bashrc"); string contents((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); string needle = "export"; // search using string::find size_t pos = contents.find(needle); cout << "location using find: " << contents.find(needle) << endl; // search using <algoritm>'s search string::const_iterator it = search(contents.begin(), contents.end(), needle.begin(), needle.end()); cout << "location found using search: " << string(it, it + 10) << endl; cout << " at position: " << it - contents.begin() << endl; 

[EDIT] You can also search with the istreambug_iterators directly, but that leaves you with the same kind of iterator.

istreambuf_iterator<char> it2 = search( istreambuf_iterator<char>(file), istreambuf_iterator<char>(), needle.begin(), needle.end()); 
Sign up to request clarification or add additional context in comments.

1 Comment

and if it is a large file just read it in sections and compensate for it ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.