【问题标题】:Changing the current directory in Linux using C++使用 C++ 在 Linux 中更改当前目录
【发布时间】:2023-04-01 03:35:01
【问题描述】:

我有以下代码:

#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) 这一行。我刚开始编程,现在才开始需要了解平台特定的功能,这是一个,所以在这件事上的任何帮助将不胜感激。

【问题讨论】:

    标签: c++ linux


    【解决方案1】:

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

    要调用你只需要做的函数:

    chdir(sDirectory.c_str());
    

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

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

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

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

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

    【讨论】:

    • 非常感谢。我在写这段代码时误解了几件事,但你已经弄清楚了。
    【解决方案2】:
    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.
    }
    

    【讨论】:

      【解决方案3】:

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

      你需要做的是chdir(sDirectory.c_str()),它将把它转换成一个C风格的字符串。 int chdir(sDirectory); 上的 int 也不是必需的。

      【讨论】:

      • 这可能是一个问题,但这不是编译器抱怨的问题。编译器抱怨sDirectory 不能用于初始化一个名为chdirint
      猜你喜欢
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      相关资源
      最近更新 更多