使用迭代器将文件的一部分复制到另一个文件
Copy a part of a file to another using iterators
我仍在练习 C++,我对文件流上的字符迭代器有疑问。
我想将文件的一部分复制到另一个(临时)文件。我想在第一个文件中找到一个特定的字符串(我使用 std::find 算法),以便知道我可以在哪里 "cut" 要复制的文件部分(希望有意义)。我的问题是,对于以下代码,我有一个我不太理解的编译错误。
我的相关代码部分如下所示:
ifstream readStream(fileName.c_str());
istreambuf_iterator<char> fStart(readStream);
istreambuf_iterator<char> fEnd;
auto position = find(fStart, fEnd, refToReplace); // refToReplace is a std::string
if (position != fEnd){ // If the reference appears in the file
ofstream tempStream("temp.fsr"); // create the temp file
copy(fStart, position , ostreambuf_iterator<char>(fluxTemp)); // and copy the part I want (before the matching string)
}
else{
continue;
}
我遇到的编译错误 "stl_algo.h":
error: no match for 'operator==' in '__first.std::istreambuf_iterator<_CharT, _Traits>::operator*<char, std::char_traits<char> >() == __val'
提前致谢。
编译错误应该带有一个实例化回溯,它会告诉您您进行的哪个调用最终导致了错误。
在您的例子中,这将指向 find
调用。 find
寻找单个元素,而你的迭代器的元素类型是单个字符,但你传递的是一个字符串。 (根据您的描述。您的代码段实际上并未告诉我们 refToReplace
的类型。)
您正在寻找的算法是 search
,但这需要前向迭代器,而 streambuf 迭代器则不需要。
您需要选择不同的方法。
我仍在练习 C++,我对文件流上的字符迭代器有疑问。
我想将文件的一部分复制到另一个(临时)文件。我想在第一个文件中找到一个特定的字符串(我使用 std::find 算法),以便知道我可以在哪里 "cut" 要复制的文件部分(希望有意义)。我的问题是,对于以下代码,我有一个我不太理解的编译错误。
我的相关代码部分如下所示:
ifstream readStream(fileName.c_str());
istreambuf_iterator<char> fStart(readStream);
istreambuf_iterator<char> fEnd;
auto position = find(fStart, fEnd, refToReplace); // refToReplace is a std::string
if (position != fEnd){ // If the reference appears in the file
ofstream tempStream("temp.fsr"); // create the temp file
copy(fStart, position , ostreambuf_iterator<char>(fluxTemp)); // and copy the part I want (before the matching string)
}
else{
continue;
}
我遇到的编译错误 "stl_algo.h":
error: no match for 'operator==' in '__first.std::istreambuf_iterator<_CharT, _Traits>::operator*<char, std::char_traits<char> >() == __val'
提前致谢。
编译错误应该带有一个实例化回溯,它会告诉您您进行的哪个调用最终导致了错误。
在您的例子中,这将指向 find
调用。 find
寻找单个元素,而你的迭代器的元素类型是单个字符,但你传递的是一个字符串。 (根据您的描述。您的代码段实际上并未告诉我们 refToReplace
的类型。)
您正在寻找的算法是 search
,但这需要前向迭代器,而 streambuf 迭代器则不需要。
您需要选择不同的方法。