【问题标题】:Unix commands with c++带有 c++ 的 Unix 命令
【发布时间】:2018-03-27 17:05:43
【问题描述】:

我需要从 C++ 程序运行 Unix 命令。

    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);

但是当我使用调用cd 命令(更改当前目录)时,我收到“权限被拒绝”错误。

我可以在我的代码中使用chmod 吗?如果是,我该如何使用它。

编译后我无法使用chmod

这就是我编译代码的方式:

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

【问题讨论】:

    标签: c++ shell unix system


    【解决方案1】:

    system() 函数启动一个新的 shell。如果你在那个 shell 中 cd 你只会影响那个 shell,一旦对 system() 的调用返回,它就会消失,所以基本上没有效果。您可能永远不应该在 C++ 程序中使用 system() - 如果您想更改执行代码的工作目录,您应该使用 POSIX 的 chdir() 函数,但我相信它也可以在 Windows 上使用..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2011-04-17
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多