你所做的事情本質上是試圖創建自己的數據庫,這種數據庫在最好情況下會適得其反。但如果是學習文件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