-2

I'm passing two std::string's to a function that is creating an alias and echoing it to bashrc in linux and having some problems.

Anyhow, since system() is expecting a char this won't work and I can't seem to figure it out, thanks in advance! (Here is a code snippet that hopefully illustrates what I'm trying to say)

#include <iostream>

int create_alias(std::string&, std::string&);

int main(void)
{

    return 0;
}

int create_alias(std::string &alias, std::string &name)
{
    #ifndef __linux__
        std::cout << "Program not  supported, aborting!";
        return 1;
    #endif
    if ( system("echo alias " + name + "='" + alias + "' >> .bashrc") != 0 )
        return 1;
    return 0;
}
isak
  • 37
  • 7

5 Answers5

1

The system function expects a const char* parameter. Form a string and then supply the pointer to a null terminated character array to the system function:

std::string s = "echo alias " + name + "='" + alias + "' >> .bashrc";
if (system(s.c_str()) != 0)
Ron
  • 14,674
  • 4
  • 34
  • 47
1

You can use the yourstring.c_str(), it returns a char *.

Also, using system() is a bad idea, you could just write to .bashrc via fstream.

atmostmediocre
  • 198
  • 1
  • 9
  • @RemyLebeau The code just uses echo to write a basic command to .bashrc, that code would be fine in a shell script, not in a C++ app. Just use basic file I/O to implement the `create_alias()` function – nos Jan 27 '18 at 22:23
  • @nos: there may be other things the program does or will do that warrant using C++. Anyway, using `ofstream` in append mode is definitely safer (and will be much faster to execute, not that it's likely to matter) than `system()`, so good answer. – Tony Delroy Jan 27 '18 at 23:43
0

to get a const char * from a string you use .c_str()

string msg="echo alias " + name + string("='" + alias + "' >> .bashrc";
system(msg.c_str());
Gabriel
  • 3,564
  • 1
  • 27
  • 49
0

Use the std::string::c_str() method to get a const char * from a std::string, eg:

int create_alias(const std::string &alias, const std::string &name)
{
    #ifndef __linux__
    std::cout << "Program not supported, aborting!";
    return 1;
    #else
    std::string cmd = "echo alias " + name + "='" + alias + "' >> .bashrc";
    if ( std::system(cmd.c_str()) != 0 )
        return 1;
    return 0;
    #endif
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

The std::string::c_str() function returns a const char* C string:

if ( system( (std::string("echo alias ") + 
              name + 
              "='" + 
              alias + 
              "' >> .bashrc").c_str() ) != 0 )
Clifford
  • 88,407
  • 13
  • 85
  • 165