0

それは難しい質問ではないと思いますが、C++の方法でそれを行う方法を知りたいです。定義された単語またはシーケンスの位置を検索したい。

私はこの投稿スタックの同様の質問を読みました、そして答えは素晴らしく見えます。しかし、このソリューションをファイルに適用する方法がわかりません。このstd命令は、またはで簡単に適用できますが、ファイルとシーケンスに適用する方法がわかりません。

命令:

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

文字列を使用して、ファイルで検索するシーケンスを保存できますか?

誰かが検索命令を適用する方法の簡単な例を投稿できますか?私はそれをコンパイルするときにいつもobatinと大きなエラーがあります。

私はウィンドウを使用せず、Boostライブラリを使用したくありません。

前もって感謝します。

4

1 に答える 1

4

ファイルを文字列に読み込みます (サイズが大きくないと仮定します)。その後、string::find または 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;

[編集] istreambug_iterators で直接検索することもできますが、同じ種類のイテレータが残ります。

istreambuf_iterator<char> it2 = search(
        istreambuf_iterator<char>(file), istreambuf_iterator<char>(),
        needle.begin(), needle.end());
于 2012-06-06T00:40:24.137 に答える