使用 C++ 的 Unix 命令 [英] Unix commands with c++

查看:40
本文介绍了使用 C++ 的 Unix 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是当我使用调用 cd 命令(更改当前目录)时,出现权限被拒绝"错误.

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

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

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

编译后我无法使用 chmod.

这是我编译代码的方式:

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

推荐答案

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

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..

这篇关于使用 C++ 的 Unix 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆