file modification in c / c++

Hello , i want to modify the file contents using C++ here is the below sample prog.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <fstream>
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
    string line;
    char buf[1024]="";
    char rembuf[1024]="";
    int found;
    snprintf(buf,sizeof(buf) -1,"/usr/CPP/textfile.txt");
//    snprintf(rembuf, sizeof(rembuf) -1, "/usr/CPP/tempfile.txt");

    ifstream in(buf);

    if(!in.is_open())
    {
          cout << "failed to open\n";
          return 0;
    }
    ofstream out;
    out.open(rembuf );  // if no file then how it will create ( in C we have 'w' flag)
    while( getline(in,line) )
    {
        found = line.find("woodfordsun.com");
        if(found == string::npos)
           out << line << "\n";
    }
    in.close();
    out.close();

   unlink(buf);
   rename(rembuf,buf);

    return 0;
}


suggest me or any help for modify the file in best method.
Note: dealing with large file
Last edited on
> if no file then how it will create ( in C we have 'w' flag)
iirc, it would end up calling http://en.cppreference.com/w/cpp/io/basic_filebuf/open
there you can see the comparison of C++ and C flags

in your case, if the `open()' operation succeed then you'll have an empty file with that name in line 24.
Note that it's preferable to use the constructor directly ofstream out( rembuf );
Last edited on
yeah i got it , i just misplaced my input text file

i had a doubt , i want to know that is this operation is suitable for modifying the big file ( lakhs of lines.)

what else the other procedure i can use in modifying the file. need to look on performance also.
Topic archived. No new replies allowed.