![](/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.