C++ 使用C+;更改Linux中的当前目录+;
我有以下代码:C++ 使用C+;更改Linux中的当前目录+;,c++,linux,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 direct
#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;
}
参考行读取int chdirectory)
。我刚刚开始编程,现在才开始了解特定于平台的函数,这是一个函数,因此非常感谢在这方面的任何帮助。if(chdirectory.c_str())==-1){
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.
}
//通过检查errno来处理这个奇妙的错误。
//您可能需要#include来访问errno全局变量。
}
问题在于,您需要将STL字符串传递给chdir()。chdir()需要一个C样式的字符串,它只是一个以NUL字节结尾的字符数组
您需要做的是chdir(sDirectory.c_str())
,它将把它转换为c样式的字符串。以及intchdirectory上的int代码>不是必需的。intchdirectory
不是调用chdir
函数的正确语法。它是名为chdir
的int
的声明,带有无效的字符串初始值设定项(`sDirectory)
要调用函数,只需执行以下操作:
chdir(sDirectory.c_str());
请注意,chdir使用的是常量char*
,而不是std::string
,因此必须使用.c_str()
如果要保留返回值,可以声明一个整数并使用chdir
调用对其进行初始化,但必须为int
指定一个名称:
int chdir_return_value = chdir(sDirectory.c_str());
最后,请注意,在大多数操作系统中,只能为进程本身及其创建的任何子进程设置当前或工作目录。它(几乎)从不影响导致进程更改其当前目录的进程
如果您希望在程序终止后发现shell的工作目录将被更改,您可能会失望。这可能是一个问题,但这不是编译器抱怨的问题。编译器正在抱怨sDirectory
无法用于初始化名为chdir
的int
。非常感谢。在编写此代码时,我误解了几点,但您已经澄清了这一点。
int chdir_return_value = chdir(sDirectory.c_str());