Searching...
Sunday, 16 June 2013

How To Remove a String From Text File Using C++ | Remove Duplicates From File.

Sunday, June 16, 2013
Here i am going to write a c++ program which helps you to remove string from a text file and also Remove Duplicates From a File. C++ coding is very easy if you know the all basics but i don’t then it is very complex to write a simple 10 lines program. Lets Come to the point and Get code for Remove Duplicates From a File.
Remove Duplicates From a File
Remove Duplicates From a File >>
Code >>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main (int _x, char *_y[])
{
   string file_ori = “/home/someuser/tipswell.txt”;
   string string_to_remove = “this is a test”;
   string line = “”;
   vector<string> lines;
   // loads file to memory
   ifstream input(file_ori.c_str(), std::ios_base::in);
   while ( std::getline(input, line, ‘\n’) )
      lines.push_back(line);
   input.close();
   // Remove string from lines
   int pos = 0;
   for ( int x = 0; x < lines.size(); x++ )
   {
      if ( (pos = lines[x].find(string_to_remove
)) != string::npos )
      {
         if ( pos == 0 )
            lines[x] = lines[x].substr(string_to_remove.size());
         else
            lines[x] = lines[x].substr(0, pos) + lines[x].substr(pos+string_to_remove.size());
      }       cout << lines[x] << “\n”;
   }
   return 0;
}
Compilation Process of Remove Duplicates From File
g++ -o sample  sample.cpp
                execute:  sample >file.txt

0 comments:

Post a Comment