![](/img/trans.png)
[英]c++ Checking if a directory exists in Unix and call void function if it exists.
[英]checking if it is windows or unix before creating a directory in C++
我寫了這段代碼來檢查Windows和Unix中是否都存在目錄,但是我不確定它是否正確:
int writeFiles(std::string location)
{
// USED TO FILE SYSTEM OPERATION
struct stat st;
// DEFINE THE mode WHICH THE FILE WILL BE CREATED
const char * mode = "w+b";
/* local curl variable */
// CHECK IF THE DIRECTORY TO WHERE THE FILE ARE GOING EXIST
// IF NOT, CREATE IT
if(stat(location.c_str(), &st) != 0){
#ifndef (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */
if (!CreateDirectory(location.c_str(), NULL)){
std::string msg("The location directory did not exists, can't be created\n");
throw std::runtime_error(msg);
}
#elif defined __unix__ /* in the case of unix system */
if(mkdir(location.c_str(), S_IRWXU) != 0){
std::string msg("The dest_loc directory did not exist, can't be created\n");
throw std::runtime_error(msg);
}
#endif
... more code down here.
location
是應該將文件復制到的路徑。 但是,在開始復制文件之前,我必須檢查Windows和Linux的目錄是否存在。 有人可以就這個問題給我一些意見嗎? 謝謝
我將預處理器指令(請參閱Microsoft預定義宏的列表)寫為:
#ifdef _WIN32
#else
// Assume UNIX system,
// depending on what you are compiling your code on,
// by that I mean you only building on Windows or UNIX
// (Linux, Solaris, etc) and not on Mac or other.
#endif
如果目錄已經存在,則CreateDirectory()
將失敗(返回FALSE
),但會將上一個錯誤設置為ERROR_ALREADY_EXISTS
。 更改對CreateDirectory()
以正確處理此問題:
if (!CreateDirectory(location.c_str(), NULL) &&
ERROR_ALREADY_EXISTS != GetLastError())
{
// Error message more useful if you include last error code.
std::ostringstream err;
err << "CreateDirectory() failure on "
<< location
<< ", last-error="
<< GetLastError();
throw std::runtime_exception(err.str());
}
話雖如此,如果您有權使用boost,請考慮使用boost::filesystem
庫。
您需要更改:
#ifndef (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */
至:
#if (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */
這將測試是否定義了_WIN32
或__WIN64
,然后使用WINAPI代碼(如果是)。
您可能還可以更改:
#elif defined __unix__ /* in the case of unix system */
只是:
#else /* in the case of non-Windows system */
因為大多數非Windows操作系統可能都具有用於mkdir
等的POSIX風格的API,並且您當前沒有任何其他特定於操作系統的代碼。
如果必須編寫與文件系統交互的跨平台代碼,則可以使用跨平台文件系統API,例如Boost FileSystem 。
如果您可以假設Windows具有stat()
,為什么還不能只使用mkdir()
呢?
但是實際上,在Windows上,您可以無條件地調用CreateDirectory
(無先前的stat
調用),並檢查GetLastError()
是否返回ERROR_ALREADY_EXISTS
。
而且, std::string
是ANSI函數CreateDirectoryA
的匹配項。 使用CreateDirectory
宏會使您容易遇到Unicode不匹配的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.