在Windows上创建目录并检查它是否存在

时间:2019-03-20 13:47:09

标签: c++ windows

我必须创建一些目录,当我尝试搜索一个目录时,我必须知道它是否已经创建。

问题是,在使用library(dplyr) res %>% select(-ends_with(".y")) %>% rename_all(~sub("\\.x$","",.)) # var_1 var_2 var_3 var_4 # 1 1995 AA AAAA A # 2 1996 AA AAAA B # 3 1995 BB BBBB C # 4 1996 BB BBBB D 创建目录并尝试检查该目录是否创建后,我收到一条错误消息,提示未创建。

如果我关闭并重新启动该程序,而不创建目录,而只是检查它是否已创建,则一切正常。

CreateDirectory()

1 个答案:

答案 0 :(得分:0)

如果marca是“数据库”,它将起作用。但是,如果marca是“ database / foo”,则不能同时创建两者。

这是您的代码的版本,我将这些操作分开。

#include <windows.h>
#include <io.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

bool DirectoryExists( const char* absolutePath )
{
    if( _access( absolutePath, 0 ) == 0 ){

        struct stat status;
        stat( absolutePath, &status );

        return (status.st_mode & S_IFDIR) != 0;
    }
    return false;
}

bool MakeDirectory(const string& marca)
{
    if(! CreateDirectory(marca.c_str(), NULL))
    {
        DWORD error = GetLastError();
        TCHAR buf[256];
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
            buf, (sizeof(buf) / sizeof(TCHAR)), NULL);
        cout << "Failed to create directory: " << buf << '\n';
        return false;
    }

    if(! DirectoryExists(marca.c_str() )  )
    {
        cout << "Directory does not exist\n";
        return false;
    }
    return true;
}

int main()
{
    // name of subdirectory
    string marca = "foo"; 

    // first create top directory
    string d = "database";
    MakeDirectory(d);

    // then subdirectory
    d += "/" + marca;
    MakeDirectory(d);

    return 0;

}

相关问题