[英]Changing the current directory in Linux using C++
我有以下代碼:
#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)
。 我剛剛開始編程,現在才開始尋找有關平台特定功能的信息,因此,對此問題的任何幫助將不勝感激。
int chdir(sDirectory);
調用chdir
函數的語法不正確。 它是一個稱為chdir
的int
的聲明,帶有無效的字符串初始化程序(`sDirectory)。
要調用該函數,您只需要執行以下操作:
chdir(sDirectory.c_str());
請注意,chdir需要一個const char*
,而不是std::string
因此您必須使用.c_str()
。
如果要保留返回值,則可以聲明一個整數並使用chdir
調用對其進行初始化,但是必須為int
命名:
int chdir_return_value = chdir(sDirectory.c_str());
最后,請注意,在大多數操作系統中,只能為進程本身及其創建的任何子級設置當前目錄或工作目錄。 它(幾乎)永遠不會影響生成更改其當前目錄的進程的進程。
如果您希望在程序終止后找到要更改的Shell工作目錄,則可能會感到失望。
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.
}
問題是您是將STL字符串傳遞給chdir()的字符串。 chdir()需要一個C樣式字符串,它只是一個以NUL字節結尾的字符數組。
您需要做的是chdir(sDirectory.c_str())
,它將轉換為C樣式字符串。 還有int chdir(sDirectory);
上的int chdir(sDirectory);
沒必要
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.