0

I need to run Unix commands from a C++ program.

    string command;
    do{
        cout<<"~ "<<get_current_dir_name ()<<">";
        cin>>command;
        if(command=="exit"||cin.eof()){
            cout<<"exit!"<<endl;
            system("exit");
            break;
        }
        system(command.c_str());
    }while (true);

But I get a "Permission denied" error when I use invoke the cd command (to change the current directory).

Can I use a chmod in my code? If yes, how can I use it.

I'm not able use chmod after compilation.

This is how I compile my code:

g++ -o shell *.cpp -std=c++11 -Wall -Wno-vla -pedantic -march=core2 -Os -pipe -fstack-protector-all -g3 -Wl,-O,1,-z,combreloc

1 Answer 1

6

The system() function starts a new shell. If you cd in that shell you only affect that shell, which goes away once the call to system() returns, and so basically has no effect. You should probably never use system() in a C++ program - if you want to change the working directory of your executing code, you should use the chdir() function which is POSIX but I believe also available on Windows..

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.