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
这意味着根据编辑的位置,几乎移动整个文件。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到