J
Juha Nieminen
I don't really understand how seeking a std::fstream affects the
stream. Consider, for instance, this program:
//-----------------------------------------------------------------
#include <fstream>
#include <string>
int main()
{
std::fstream stream("file.txt");
if(!stream) return 1;
const std::string keyword = "hello";
const std::string replacement = "HELLO";
std::string line;
while(std::getline(stream, line))
{
size_t ind = line.find(keyword);
if(ind != line.npos)
{
stream.seekp
(size_t(stream.tellg()) - line.length() + ind - 1);
stream.write(replacement.c_str(), replacement.length());
}
}
}
//-----------------------------------------------------------------
The idea is that it would scan through a file and replace the first
appearance of "hello" in each line with "HELLO".
Problem: It makes the replacement in the first line that matches, and
then stops. I don't really understand why.
If I add "stream.seekg(stream.tellp());" after the write, then it
works as expected. However, I don't understand why I have to do that.
(Yes, I know the above code is not very portable because it assumes
that the newline character is only one byte long. Please don't nitpick
about that.)
stream. Consider, for instance, this program:
//-----------------------------------------------------------------
#include <fstream>
#include <string>
int main()
{
std::fstream stream("file.txt");
if(!stream) return 1;
const std::string keyword = "hello";
const std::string replacement = "HELLO";
std::string line;
while(std::getline(stream, line))
{
size_t ind = line.find(keyword);
if(ind != line.npos)
{
stream.seekp
(size_t(stream.tellg()) - line.length() + ind - 1);
stream.write(replacement.c_str(), replacement.length());
}
}
}
//-----------------------------------------------------------------
The idea is that it would scan through a file and replace the first
appearance of "hello" in each line with "HELLO".
Problem: It makes the replacement in the first line that matches, and
then stops. I don't really understand why.
If I add "stream.seekg(stream.tellp());" after the write, then it
works as expected. However, I don't understand why I have to do that.
(Yes, I know the above code is not very portable because it assumes
that the newline character is only one byte long. Please don't nitpick
about that.)