你所做的事情本质上是试图创建自己的数据库,这种数据库在最好情况下会适得其反。但如果是学习文件I/O和字符串流,下面的代码可以帮助你理解概念,尽管它可能不是最有效的做事方式。
在一般情况下,@Murphy说,你需要阅读的文件,将其复制到缓冲区,调整缓冲区根据自己的喜好,截断该文件,写自己的缓冲区里的文件。
int searchbyID(string filename, string ID, string newName);
int main()
{
searchbyID("d:\\test.txt", "2", "silmarillion");
}
int searchbyID(string filename, string ID, string newName)
{
// open an input file stream
ifstream inputfile(filename);
if (!inputfile)
return -1; // couldn't open the file
string line,word;
string buffer;
// read the file line by line
while (getline(inputfile, line))
{
std::stringstream record(line);
//read the id from the file and check if it's the asked one
record >> word;
if (word == ID)
{
// append the ID first
buffer += ID + "\t";
//append the new name instead of the old one
buffer += newName + "\t";
//pass the old name
record >> word;
//copy the rest of the line just as it is
while (record >> word)
buffer += "\t" + word + "\t";
buffer += "\n";
}
else
{
//if not, just pass the line as it is
buffer += line + "\n";
}
}
// close input file stream
inputfile.close();
// open an output file stream
ofstream outputfile(filename);
// write new buffer to the file
outputfile << buffer;
//close the output file stream
outputfile.close();
return 0;
}
你必须读取文件并解析它。查询您感兴趣的项目,修改它并将整个内容保存到文件中。实施取决于您选择哪一个最适合您使用。有一些库可以用来简化STL,boost或QT等库。 –
@rafaelgonzalez我很新的编程,所以我不知道你说的大部分 – MiDo
考虑使用SQLite数据库。 – 2017-08-12 18:42:16