如何用 fstream 替换特定行?
How can I replace a especific line with fstream?
我有这个:
std::fstream fullscreenData("variables/fullscreenData.txt", std::ios::in | std::ios::out);
while (std::getline(fullscreenData, *streamString)) {
*streamString = static_cast<std::string>("Fullscreen: false");
if (*streamString == static_cast<std::string>("Fullscreen: false")) {
fullscreenData << "Fullscreen: true\n";
}
}
fullscreenData.close();
我正在测试,我可以使用 "while" 和 "if" 从 txt 中读取,并使用 "fullscreenData <<" 在 txt 中写入。
但是我一起用就不行了,txt里面什么也没有写
有人知道我做错了什么吗?
您的数据类型有问题。
您可能想尝试这样的事情:
std::streampos position_line_begin(0);
std::string text;
while (std::getline(fullScreenData, text))
{
if (text == "Fullscreen: false")
{
fullScreenData.seekp(position_line_begin);
fullScreenData << "Fullscreen: true \n";
break;
}
position_line_begin = fullScreenData.tellg();
}
有更好的方法,但这演示了算法。
我有这个:
std::fstream fullscreenData("variables/fullscreenData.txt", std::ios::in | std::ios::out);
while (std::getline(fullscreenData, *streamString)) {
*streamString = static_cast<std::string>("Fullscreen: false");
if (*streamString == static_cast<std::string>("Fullscreen: false")) {
fullscreenData << "Fullscreen: true\n";
}
}
fullscreenData.close();
我正在测试,我可以使用 "while" 和 "if" 从 txt 中读取,并使用 "fullscreenData <<" 在 txt 中写入。 但是我一起用就不行了,txt里面什么也没有写
有人知道我做错了什么吗?
您的数据类型有问题。
您可能想尝试这样的事情:
std::streampos position_line_begin(0);
std::string text;
while (std::getline(fullScreenData, text))
{
if (text == "Fullscreen: false")
{
fullScreenData.seekp(position_line_begin);
fullScreenData << "Fullscreen: true \n";
break;
}
position_line_begin = fullScreenData.tellg();
}
有更好的方法,但这演示了算法。