Delete duplicate rows in the file
It is actually a very simple operation. It is written here because I have been readingThinking in C ++ Volume 2For the iostream chapter, as an exercise, so write it out. J
Define constants first
Const int unique_lines_ OK = 0;
Const int unique_lines_error = 1;
Const int file_open_error = 2;
The following function int ulisf (const string & strfilename) is used, where
The const string & strfilename parameter is the file name;
Return Value
Unique_lines_ OK: the repeated rows in the file are successfully deleted;
Unique_lines_error: file write error;
File_open_error: failed to open the file.
The function is as follows:
Int ulisf (const string & strfilename)
{
Int iret = unique_lines_ OK;
Set <string> setstrlines; // The string set
String strreadline; // temporary string read from the file
// Read each lines from the file -- begin --
Ifstream fin (strfilename. c_str (); // read the file
If (! Fin) // verify open
{
Iret = file_open_error;
Return iret;
}
While (Getline (FIN, strreadline ))
{
Setstrlines. insert (strreadline );
}
Fin. Close ();
// Read each lines from the file -- end --
// Delete the file
Remove (strfilename. c_str ());
// Write the strings of the set into the file -- begin --
Ofstream fout (strfilename. c_str (); // write the file
If (! Fout) // verify open
{
Iret = file_open_error;
Return iret;
}
Set <string >:: iterator it;
For (IT = setstrlines. Begin (); it! = Setstrlines. End (); It ++)
{
Fout <it-> c_str () <Endl;
}
Fout. Close ();
// Write the strings of the set into the file -- end --
Return iret;
}
Because files in the C ++ standard library are used, header files need to be added.
# Include <iostream>
# Include <string>
# Include <set>
# Include <fstream>
# Include <iterator>
(End)