[英]std::rename() file wont work when using a char variable as arguments (string converted to char)
[英]Converted string to char, when i cout the char it is correct but when I use chdir with the char it does not work?
我正在開發一個程序,該程序可以打印工作目錄和更改目錄。 最初,我讓用戶鍵入“ cd”,這將調用cd函數並詢問他們要更改到的目錄。 這很好用,但是我希望能夠在一行中全部完成“ cd / Users”之類的操作。 我已經成功地分割了字符串,並將分割后的部分傳遞給我正在使用的chdir字符變量,但是由於某種原因,chdir實際上並未使用此方法更改目錄。
`void exec_cd(std::string destination)
{
int BUFFER_SIZE = 1024;
char *directory;
directory = new char [BUFFER_SIZE]; //Allocated memory in order to cin to the pointer char
strcpy(directory, destination.c_str()); //Copy destination string into char directory
//std::cout << "Enter target directory: " << std::endl << ">";
//std::cin >> directory;
std::cout << "TEST: " << directory;
chdir(directory);
delete [] directory;
}`
我注釋掉了我的舊行,當這些行在那里而不是strcpy時運行良好。 此函數將傳遞到cd之后輸入的所有內容,我知道strcpy會執行其工作,因為帶有“ TEST:”的行將輸出應有的結果(例如,我鍵入cd / Users),它將顯示目錄確實包含'/ Users '由於某種原因,它不能與chdir一起使用。 據我所知,我有一個pwd函數可以正常工作,但我也會在此處發布它。
void exec_pwd()
{
long size;
char *buf; //buffer holder
char *ptr; //where the current directory will be saved to
size = pathconf(".", _PC_PATH_MAX); //Gets size of path and saves it to size var.
if ((buf = (char *)malloc((size_t)size)) != NULL) //Set buff = size of char * allocated size, if not null then get wd
ptr = getcwd(buf, (size_t)size);
std::cout << ptr << std::endl;
}
確認目標目錄中有空白,並添加了修剪功能以消除問題前后的空間。
您可能會發現盡快將OS錯誤轉換為error_code
會有所幫助。
#include <unistd.h>
#include <cerrno>
#include <system_error>
#include <iostream>
std::error_code change_directory(std::string const& str)
{
std::error_code result;
if(chdir(str.c_str()))
{
result = std::error_code(errno, std::system_category());
}
return result;
}
void throw_on_failure(std::error_code ec)
{
if (ec) throw std::system_error(ec);
}
int main(int argc, char** argv)
{
try
{
throw_on_failure(change_directory(argv[1]));
}
catch(std::exception const& e)
{
std::cout << e.what() << '\n';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.