C 在文件中的特定行上写入

C++ Write on a Specific Line in a File

本文关键字:文件      更新时间:2023-10-16

现在,我能够读取文件的特定行,但是问题是,如何在文件中的同一特定行上写入?例如,假设第1行说"测试",第2行说"恭喜",第3行"是的",我该如何将其替换为" Yess"或" Yess"或其他形式的内容。顺便说一句,在我的int main()代码中,我调用readline(0);并检查行是否为零,我打电话给if(linenumber == 0);提前致谢!

void readLine(int lineNum) {
    ifstream fin("StartupMap.dat");
    string s;
    long length;
    fin.seekg (0, ios::beg); // go to the first line
    for (int i = 0; i <= lineNumber; i++) // loop 'till the desired line
        getline(fin, s);
    if (lineNumber == 0)
        true1 = true;
    length = fin.tellg(); // tell the first position at the line, maybe +1 or -1. try if it's not working
    fin.seekg(length);
    lineNumber = lineNum;
}

文件只是字符流。这意味着,如果您想使线路更长,那么您必须在该线路前移动中出现的所有内容以使空间。相反

它效率非常低。

避免这种情况的唯一实用方法

是确保所有行均为固定长度。

否则,您要么需要在整个文件中读取并在编辑后再次写入它,要么将文件复制到新文件,然后随时更改。

例如:

文件中的3行可能看起来像这样:

TestnCongratznYay
0     5         14   <- start position of line
Line 1 is "Test"
Line 2 is "Congratz"
Line 3 is "Yay"

如果要更改第2行以说"是",则需要向后移动第三行:

TestnYessnYay <= now line 3 starts sooner
0     5     10  <- start position of line

这意味着根据编辑的位置,几乎移动整个文件。