简体   繁体   English

在C ++中创建目录之前检查它是Windows还是Unix

[英]checking if it is windows or unix before creating a directory in C++

I wrote this piece of code to check if a directory exists in both Windows and Unix, but I'm not sure whether it is correct: 我写了这段代码来检查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 is the path to where the files are supposed to copied. location是应该将文件复制到的路径。 However, before I start copying the files, I have to check whether the directory exists or not, for both Windows and Linux. 但是,在开始复制文件之前,我必须检查Windows和Linux的目录是否存在。 Could someone please give me some input on that problem? 有人可以就这个问题给我一些意见吗? Thanks 谢谢

The preprocessor directives (see list of Microsoft Predefined Macros ) I would write as: 我将预处理器指令(请参阅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

The CreateDirectory() will fail (return FALSE ) if the directory already exists but will set the last error to ERROR_ALREADY_EXISTS . 如果目录已经存在,则CreateDirectory()将失败(返回FALSE ),但会将上一个错误设置为ERROR_ALREADY_EXISTS Change your use of CreateDirectory() to handle this correctly: 更改对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());
}

Having said that, if you have access to boost consider using the boost::filesystem library. 话虽如此,如果您有权使用boost,请考虑使用boost::filesystem库。

You need to change: 您需要更改:

            #ifndef (defined  _WIN32 || defined __WIN64)    /* WIN32 SYSTEM */

to: 至:

            #if (defined _WIN32 || defined __WIN64)    /* WIN32 SYSTEM */

This tests whether either _WIN32 or __WIN64 is defined and then uses the WINAPI code if that is the case. 这将测试是否定义了_WIN32__WIN64 ,然后使用WINAPI代码(如果是)。

You could probably also change: 您可能还可以更改:

            #elif defined __unix__          /* in the case of unix system */

to just: 只是:

            #else          /* in the case of non-Windows system */

since most non-Windows OS are likely to have POSIX-ish APIs for mkdir etc, and you currently don't have any other OS-specific code. 因为大多数非Windows操作系统可能都具有用于mkdir等的POSIX风格的API,并且您当前没有任何其他特定于操作系统的代码。

如果必须编写与文件系统交互的跨平台代码,则可以使用跨平台文件系统API,例如Boost FileSystem

If you can assume that Windows has stat() , why can't you also just use mkdir() ? 如果您可以假设Windows具有stat() ,为什么还不能只使用mkdir()呢?

But really, on Windows you can call CreateDirectory unconditionally (no preceding stat call) and check whether GetLastError() returns ERROR_ALREADY_EXISTS . 但是实际上,在Windows上,您可以无条件地调用CreateDirectory (无先前的stat调用),并检查GetLastError()是否返回ERROR_ALREADY_EXISTS

Also, std::string is a match for the ANSI function, CreateDirectoryA . 而且, std::string是ANSI函数CreateDirectoryA的匹配项。 Using the CreateDirectory macro leaves you open to Unicode mismatch. 使用CreateDirectory宏会使您容易遇到Unicode不匹配的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM