My problem is that I have to modify a record in a text file. Suppose there are 10 records in a file and I have modify the 5th record. I am trying to do this with the help of tellg and seekp.
Whenever I use fout.open("filename"), the previous contents of the file are discarded/deleted. Which filemode do I use which allows me to use seekp and at the same time, doesn't delete the contents of the file. I cannot use ios::app because seekp can't be used then. Even ios::ate is deleting the contents of the file.
If there is no file mode to do this, then I can think of only one solution, i.e. to copy till the 4th record to another file, write the modified 5th record to the second file, and then write the remaining records from the first file to second file. After this, remove the first file and rename the second file.
The way to do it is to read the data into memory, modify it in memory and then write it back out. e.g.
const char* filename = "file.txt";
//Read data into string object and then close the file
//print the file if you like
//std::cout << data << std::endl;
//modify data here...
//write the modified data to the file
std::cout << "Unable to open " << filename << " for writing!" << std::endl;
std::cout << "Unable to open " << filename << " for reading!" << std::endl;