What you are doing is, essentially, trying to create your own database which is counterproductive at best. But if it's for learning file I/O and string streams, following code can help you understand the concepts although It's probably not the most efficient way of doing things.
In general, as @Murphy said, you need to read a file, copy it to a buffer, adjust the buffer to your liking, truncate the file and write your own buffer to the file.
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;
}