I've stored data in a text file, but I've got a requirement if the input, say a is seen in the file already( I know how to do that), delete the line, how would I do that?
Unless the file is really gigantic: read the contents of the file into a vector, erase items we don't want from the vector, and write the items remaining into the file.
#include <iostream> // **** this is the first line
#include <string>
#include <vector>
#include <fstream>
// read the lines in the stream (file) into a vector
std::vector<std::string> read_lines( std::istream& stm )
{
std::vector<std::string> lines_read ;
std::string line ;
while( std::getline( stm, line ) ) lines_read.push_back(line) ;
return lines_read ;
}
// write the lines in the vector into a stream (file)
bool write_lines( std::ostream& stm, const std::vector<std::string>& lines_to_be_written )
{
for( const std::string& line : lines_to_be_written ) stm << line << '\n' ;
return stm.good() ;
}
int main()
{
const std::string input_file_name = __FILE__ ;
const std::string output_file_name = __FILE__ ".modified.txt" ;
if( std::ifstream input_file{input_file_name} )
{
auto lines = read_lines(input_file) ; // read contents of the file into a vector
// erase the lines we don't want from the vector. for example
if( !lines.empty() ) lines.erase( lines.begin() ) ; // erase the first line
if( !lines.empty() ) lines.erase( --lines.end() ) ; // erase the last line
// write the lines remaining in the vector into the output_file
if( std::ofstream output_file{output_file_name} )
if( write_lines( output_file, lines ) ) std::cout << "success: output file was was written\n" ;
}
}
// *** this is the last line
#include <iostream>
#include <string>
#include <fstream>
int main()
{
const std::string input_file_name = __FILE__ ;
const std::string output_file_name = __FILE__ ".modified.txt" ;
std::ifstream input_file{input_file_name} ;
std::ofstream output_file{output_file_name} ;
if( input_file && output_file )
{
std::string line ;
while( std::getline( input_file, line ) ) // for each line read from the input file
{
// check if this line is to be erased, if so do nothing
// otherwise write this line to the output file
output_file << line << '\n';
}
}
}
I've stored data in a text file, but I've got a requirement if the input, say a is seen in the file already
Can you clarify this? Do you mean that you need to remove all duplicate lines from the data file, or just duplicates that match some input string? If it's the latter, then you just need to track whether you've seen the input line already.
Also, does the output data need to be in the same order as the input? If not then it's a shell script:
sort | uniq
Last, is the input data in any particular order, or is it completely random?