使用C ++更改Linux中的当前目录

时间:2010-09-19 18:53:29

标签: c++ linux

我有以下代码:

#include <iostream>
#include <string>
#include <unistd.h>

using namespace std;

int main()
{
    // Variables
    string sDirectory;

    // Ask the user for a directory to move into
    cout << "Please enter a directory..." << endl;
    cin >> sDirectory;
    cin.get();

    // Navigate to the directory specified by the user
    int chdir(sDirectory);

    return 0;
}

此代码的目的非常简单:将用户指定的目录设置为当前目录。我的计划是对其中包含的文件进行操作。但是,当我尝试编译此代码时,我收到以下错误

error: cannot convert ‘std::string’ to ‘int’ in initialization

参考阅读int chdir(sDirectory)的行。我刚刚开始编程,现在才开始了解平台特定的功能,这一点,所以对此问题的任何帮助都将非常感激。

3 个答案:

答案 0 :(得分:8)

int chdir(sDirectory);不是调用chdir函数的正确语法。它是int的声明chdir,带有无效的字符串初始值设定项(`sDirectory)。

要调用您必须执行的功能:

chdir(sDirectory.c_str());

请注意,chdir需要const char*,而不是std::string,因此您必须使用.c_str()

如果你想保留返回值,你可以声明一个整数并使用chdir调用来初始化它,但你必须给int一个名字:

int chdir_return_value = chdir(sDirectory.c_str());

最后请注意,在大多数操作系统中,只能为进程本身及其创建的任何子进程设置当前目录或工作目录。它(几乎)永远不会影响产生更改其当前目录的进程的进程。

如果您希望在程序终止后找到要更改的shell的工作目录,则可能会感到失望。

答案 1 :(得分:5)

if (chdir(sDirectory.c_str()) == -1) {
    // handle the wonderful error by checking errno.
    // you might want to #include <cerrno> to access the errno global variable.
}

答案 2 :(得分:2)

问题是你是一个将STL字符串传递给chdir()的字符串。 chdir()需要一个C Style字符串,它只是一个以NUL字节结尾的字符数组。

您需要做的是chdir(sDirectory.c_str()),它会将其转换为C Style字符串。而int chdir(sDirectory);上的int也没有必要。