Open the file for reading. Read in all of the file except the last line. Close the file. Open the file for output (truncating the file.) Write your data to the file.
> but is it a efficient way?
> if tf file contains 1000 of line....
Yes. A few thousand lines is nothing; you wouldn't even notice the elapsed time.
If the file is a few dozen megabytes in size, something like this (Unix, Linux, Cygwin, GNUWin32):
1 2 3 4 5 6 7 8
// delete last line from file foo.txt
std::system( "/usr/bin/head -n -1 foo.txt > /tmp/temp_foo.txt && mv /tmp/temp_foo.txt foo.txt" ) ;
// delete last 5 lines from file foo.txt
std::system( "/usr/bin/head -n -5 foo.txt > /tmp/temp_foo.txt && mv /tmp/temp_foo.txt foo.txt" ) ;
// delete first 7 lines from file foo.txt
std::system( "/usr/bin/tail -n -7 foo.txt > /tmp/temp_foo.txt && mv /tmp/temp_foo.txt foo.txt" ) ;
If the file is really huge, you might want to take the stat - seek and read last chunk of file - determine the offset of last line(s) - ftruncate()
(GetFileSize - seek, read - SetEndOfFile on Windows)
route.
So read and write i done but while append, I just want to remove last line
i.e. </ServerList>
then append new server info and again at the end have to put that line - </ServerList>.
> I don't think you want to delete the last line of an XML file...
> ...
> Which is a totally invalid file.
It is clear that ak16 does not want to just delete the last line of an XML file.
And no one else has stated that the last line of an XML file should be deleted.
What was wanted was very clearly stated by ak16:
So read and write i done but while append, I just want to remove last line i.e. </ServerList>
then append new server info and again at the end have to put that line - </ServerList>.
Which, broken down into steps is:
1 2 3
a. remove last line i.e. </ServerList>
b. append new server info
c. and at the end put that line - </ServerList>
Also made quite clear from the comments in the posted code:
1 2 3 4 5
// knock off the last line
.....
// append more lines
....
// put back the last line