【发布时间】:2023-03-14 17:35:01
【问题描述】:
以下代码适用于双向流,并从文件中查找记录 ID,然后从文件中替换该记录的内容。但在覆盖内容之前,它会将 put 指针移动到 get 指针的位置。通过tellp()和tellg()发现它们在移动之前已经在同一个位置。但是在删除 seekp() 行时,代码不会覆盖数据。
data.txt 中的内容:
123 408-555-0394
124 415-555-3422
263 585-555-3490
100 650-555-3434
代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int inID = 263;
const string& inNewNumber = "777-666-3333";
fstream ioData("data.txt");
// Loop until the end of file
while (ioData.good()) {
int id;
string number;
// Read the next ID.
ioData >> id;
// Check to see if the current record is the one being changed.
if (id == inID) {
cout << "get pointer position " << ioData.tellg() << endl; //Displays 39
cout << "put pointer position " << ioData.tellp() << endl; //Displays 39
ioData.seekp(ioData.tellg()); //Commenting this line stops code from working
ioData << " " << inNewNumber;
break;
}
// Read the current number to advance the stream.
ioData >> number;
}
return 0;
}
问题:
当 get 和 put 指针一起移动时,如果 put 指针已经存在,那么需要使用 seekp() 来移动它的位置吗?
【问题讨论】:
-
由于
fstream是根据内部 C 设施定义的,因此这是相关的:stackoverflow.com/questions/1713819/… -
@Revolver_Ocelot 谢谢,我没有得到这样的推荐
标签: c++ file-access