ifstream i(filename);
... code to read and make changes
i.close();
ofstream(filename)
... code to write the new data over the old data, updating the file.
I have no idea what you mean by void(). if you put the code into functions, which you would if this is more than a few lines in main as a microprogram, and if those functions do not return any values, their type should be void. void is, in general, just a placeholder keyword for 'nothing' or 'unknown' or even 'don't care' --- a void function returns 'nothing', a void pointer has no type (void is again placeholder for type here), and so on.
My code is something like this. Trying to figure out your answer but got confused by it.
1 2 3 4 5 6 7 8 9 10
cout << "Would you like to update?" << endl;
cin >> choice;
if (choice == y){
//planning to update the file when user press y
}
else{
cout << "There is no data" << endl;
}
The thing that's hard to understand about files is that when you want to make a change, you have to rewrite the entire file, or at least the part from the change to the end.
If jonnin's suggested method isn't appropriate, here's another one that might be. The idea is to read the input file and write the modified data to a temp file. When done, you rename the temp file to the original file name. This assumes that the file contains lines that might change, but the idea applies to any sort of repeated data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ifstream i(fileName);
ofstream o(tempFilename);
while (getline(i, line)) {
if (this line needs to change) {
do_changes(line);
o << line << '\n';
} elseif (this line should be removed) {
// do nothing
} else { // this line doesn't change
// o << line << '\n';
}
i.close();
o.close();
// Now rename the tempFile to the original file
remove(fileName);
rename(tempFilename, fileName);