-
File IO
I have created a file(file.dat) and have written the following 3 lines.Later i want to delete the second line in the following way-but this is not happening. When i open the file some garbage is being shown and i see no lines which was written at the starting.May i know where i am wrong?
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout("file.dat",ios::out);
fout << "Sunanda 5 \n";
fout << "Rahool 10 \n";
fout << "Sunetra 12 \n";
fout.close();
ofstream fapp("file.dat",ios::out);
fapp.seekp(23);
int i = 0;
while(i < 11)
{
fapp << '\b';
i++;
}
fapp.close();
system("pause");
}
-
Thera are a couple of mistakes in your code.
First of all
Code:
ofstream fapp("file.dat",ios::out);
truncates the file. So the following code operates on an empty file.
you would have to use
Code:
ofstream fapp("file.dat",ios::out|ios::app);
In that case the file would not be cleared when opened.
But I guess that the effect would still not be what you want. Your code would just append a series of backspace characters to the end of the file.
If you want to remove a line from the file you have to read in the complete file and write it again without the line that you want to remove.
Kurt