C++ 在C+中创建目录之前,检查它是windows还是unix+;
我编写这段代码是为了检查Windows和Unix中是否都存在目录,但我不确定它是否正确:C++ 在C+中创建目录之前,检查它是windows还是unix+;,c++,operating-system,C++,Operating System,我编写这段代码是为了检查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";
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的目录是否存在。有人能给我一些关于这个问题的意见吗?
谢谢如果我必须编写与文件系统交互的跨平台代码,我将使用跨平台文件系统API,如。预处理器指令(请参阅列表)我将编写为:
#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
如果目录已存在,则将失败(返回FALSE
),但将最后一个错误设置为error\u ready\u 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());
}
if(!CreateDirectory(location.c_str(),NULL)&&
错误\u已\u存在!=GetLastError()
{
//如果包含最后一个错误代码,则错误消息更有用。
标准::ostringstream错误;
err如果您可以假设Windows有stat()
,为什么不能同时使用mkdir()
但实际上,在Windows上,您可以无条件地调用CreateDirectory
(没有前面的stat
调用),并检查GetLastError()
返回的ERROR\u是否已经存在
另外,std::string
与ANSI函数CreateDirectoryA
匹配。使用CreateDirectory
宏会导致Unicode不匹配。您需要更改:
#ifndef (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */
致:
这将测试是否定义了\u WIN32
或\u WIN64
,如果是这样,则使用WINAPI代码
您可能还可以更改:
#elif defined __unix__ /* in the case of unix system */
只是:
#else /* in the case of non-Windows system */
由于大多数非Windows操作系统可能都有POSIX ish API用于mkdir
等,而您目前没有任何其他特定于操作系统的代码。您不确定哪一位?@hmjd#ifndef部分…我不确定它是否能处理这两种情况(Windows和Unix)你试过使用boost.filesystem吗?\ifndef
应该是。\n如果也为WIN64目标定义了WIN32…@djechlin,\u WIN32
是在64位上定义的。它是\u WIN32
,而不是\u WIN32
。
#else /* in the case of non-Windows system */