无法写入 fstream 文件

cant write to fstream file

本文关键字:fstream 文件      更新时间:2023-10-16
void readersWriters::WriteLine(int lineNumber, std::string newLine)
{
    fstream file(_fileName, std::fstream::out | std::fstream::in);
    if (file.is_open())
    {
        int count = 1;
        string line_data;
        bool found = false;
        while (!file.eof() && !found)
        {
            getline(file, line_data);
            if (count == lineNumber)
            {
                writeLock();
                found = true;
                if (line_data.length() > newLine.length())
                    newLine += line_data.substr(newLine.length(), line_data.length());
                file << newLine; 
                getline(file, line_data);
                writeUnlock();
            }
            count++;
        }
        file.close();
        if (!found)
        {
            cout << ERROR_WRITE << endl;
        }
    }
}

我正在尝试写入 fstram 文件,该函数运行没有任何错误,但文件保持不变。我不明白为什么会:(发生。感谢您的减半:)

您不能以这种方式就地修改文件。最简单的方法是将文件作为字符串向量(每行一个字符串)读取,修改内存中的行,然后再次保存这些行。