views:

73

answers:

1

Hello. I am a beginner, and wrote the following program for fun, to search through a directory and replace every occurrence of one word with another. I call the crt_ls_file() function once, and once only, but gprof tells me it is being called 102 times. I am wondering if anyone knows why this is. I have tried compiling the program will all and no optimizations.

#include <iostream>
#include <string>
#include <cstdlib>
#include <cassert>
#include <fstream>
using namespace std;

void crt_ls_file(const string& output_f, const string& dir);
void sed(const string& old_string, const string& new_string, const string& filename, const string& directory);

int main(int argc, char* argv[]){

    string out_f;
    if  (argc <= 1) {
        cout << "Usage: " << argv[0] << " <Filename>" << endl;
        exit(EXIT_FAILURE);
    } else {
        out_f =  ".sandr";
        crt_ls_file(out_f, string(argv[1]) );
    }

    ifstream out_fs( out_f.c_str() );
    string line;
    getline(out_fs, line);
    while( !out_fs.eof() ){
        sed(string("index_SYMBOL"), string("index1_SYMBOL"), line, string(argv[1]) );
        getline(out_fs, line);
    }
    out_fs.close();
    string f( "rm " + out_f );
    system ( f.c_str() );

    exit(EXIT_SUCCESS);
}

void crt_ls_file(const string& s, const string& a){
    ofstream ls( s.c_str() );
    ls.close();
    string ls_output( "ls -1 " + a + " > ./" + string(s) );
    system( ls_output.c_str() );
}

void sed(const string& o, const string& n, const string& f, const string& d){
    ofstream dummy(".temp");
    dummy.close();

    string sed_output( "sed 's/" + o + "/" + n + "/g' " + d + "/" + f + " > .temp" );
    system( sed_output.c_str() );
    string rp( "mv .temp " + d + "/" + f );
    system ( rp.c_str() );
}
+1  A: 

On my system gprof shows only one call to crt_ls_file as it should be:

  0.00      0.00     0.00        1     0.00     0.00  crt_ls_file(std::string const&, std::string const&)

So it seems you gprof is lying, which it sometimes does. If you really want to profile this program (there's little use), try callgrind and kcachegrind instead. They're much better and less arcane tools:

$ valgrind --tool=callgrind ./my_program some_dir
... let it do its job ...
$ kcachegrind
Thomas