我正在嘗試為CD我稱為 POSH(Pine 自己的 shell)的 shell創建一個命令。
如果前一個cd命令沒有以 a 結尾/,它將附加兩個路徑并拋出(cd pine然后cd src會出錯,因為路徑將是/home/dingus/pinesrc而不是/home/dingus/pine/src)。
我知道為什么會發生這種情況,但似乎無法解決。
這是源代碼:
inline void cd(string cmd)
{
if(cmd.length() < 3) return;
string arg = cmd.substr(3);
if(fs::is_directory(fs::status( string(path).append(arg))))
{
path.append(arg);
}
else cout << "Error: \"" << arg << "\" is not a directory" << endl;
}
uj5u.com熱心網友回復:
string(path).append(arg)正在執行字串連接。您沒有在檔案系統元素之間附加任何您自己的斜線。因此,如果pathis /home/dingus/,cd pine則將只附加pine到最后生產/home/dingus/pine,然后cd src只會附加src到最后生產/home/dingus/pinesrc,正如您所觀察到的。
你需要做更多這樣的事情:
string curr_path;
inline void cd(string cmd)
{
if (cmd.length() < 4) return;
string arg = cmd.substr(3);
string new_path = curr_path;
if ((!new_path.empty()) && (new_path.back() != '\\')) {
new_path = '\\';
}
new_path = arg;
if (fs::is_directory(fs::status(new_path))) {
curr_path = new_path;
}
else {
cout << "Error: \"" << arg << "\" is not a directory" << endl;
}
}
但是,由于您<filesystem>無論如何都在使用該庫,因此您應該使用std::filesystem::path(特別是因為std::filesystem::status()只接受std::filesystem::path開始)。讓庫為您處理任何路徑連接,例如:
fs::path curr_path;
inline void cd(string cmd)
{
if (cmd.length() < 4) return;
string arg = cmd.substr(3);
fs::path new_path = curr_path / arg;
if (fs::is_directory(new_path)) {
curr_path = new_path;
}
else {
cout << "Error: \"" << arg << "\" is not a directory" << endl;
}
}
std::filesystem::pathoperator/如果斜線不存在,則實作插入斜線。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352412.html
下一篇:結構陣列僅采用C中的最后一個值
