c语言 不存在则创建文件夹,C语言判断文件所在路径和目录是否存在,不存在则创建...

在编程的时候,我们经常会需要生成一些文件,而这些文件为了方便管理,会创建多级目录,有的时候文件所在的目录没有创建,比较麻烦,直接上代码

#ifdef WIN32

// 核查目录,若目录不存在,创建目录

bool GF_FindOrCreateDirectory( const char* pszPath )

{

WIN32_FIND_DATA fd;

HANDLE hFind = ::FindFirstFile( pszPath, &fd );

while( hFind != INVALID_HANDLE_VALUE )

{

if ( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )

{

::FindClose(hFind);

return true;

}

}

if ( !::CreateDirectory( pszPath, NULL ) )

{

char szDir[MAX_PATH];

sprintf_s( szDir, sizeof(szDir), "创建目录[%s]失败,请检查权限", pszPath );

::FindClose(hFind);

return false;

}

::FindClose(hFind);

return true;

}

// 遍历目录

bool GF_CheckDirectory( char* pszFilePath )

{

char pszPath[4096];

strcpy(pszPath,pszFilePath);

(strrchr(pszPath,'\\'))[1] = 0;

vector< std::string > vtPath;

const char* sep = "\\/";

char* next_token;

char* token =  strtok_s( pszPath, sep, &next_token);

while( token != NULL )

{

vtPath.push_back( token );

token = strtok_s(NULL, sep, &next_token);

}

if ( vtPath.size() > 0 )

{

if ( vtPath[0] == "." )

vtPath.erase( vtPath.begin() );

}

// 核查所有路径是否存在

std::string strCurPath;

for( size_t i = 0; i  < (int)vtPath.size(); ++i )

{

strCurPath += vtPath[i];

if ( !GF_FindOrCreateDirectory( strCurPath.c_str() ) )

{

return false;

}

strCurPath += '\\';

}

return true;

}

#else

// 核查目录,若目录不存在,创建目录

bool GF_FindOrCreateDirectory( const char* pszPath )

{

DIR* dir;

if(NULL==(dir=opendir(pszPath)))

mkdir(pszPath,0775);

closedir(dir);

return true;

}

// 检测文件路径中的目录是否存在,不存在则创建

bool GF_CheckDirectory( char* pszFilePath )

{

char pszPath[4096];

strcpy(pszPath,pszFilePath);

(strrchr(pszPath,'/'))[1] = 0;

vector< std::string > vtPath;

const char* sep = "\\/";

char* next_token;

char* token =  strtok_r( pszPath, sep, &next_token);

while( token != NULL )

{

vtPath.push_back( token );

token = strtok_r(NULL, sep, &next_token);

}

if ( vtPath.size() > 0 )

{

if ( vtPath[0] == "." )

vtPath.erase( vtPath.begin() );

}

// 核查所有路径是否存在

std::string strCurPath;

for( size_t i = 0; i  < (int)vtPath.size(); ++i )

{

strCurPath += '/';

strCurPath += vtPath[i];

if ( !GF_FindOrCreateDirectory( strCurPath.c_str() ) )

{

return false;

}

}

return true;

}

#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值