Mkdir
一个 Mkdir 函数。可用于创建递归目录。
实验环境: linux+ gcc3.2
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <vector>
using namespace std;
int Mkdir( const char *pathname, mode_t mode )
{
char* pPath = NULL;
vector< const char* > folders ;
if ( ( pPath = (char*)malloc( strlen( pathname ) + 2 ) ) == NULL )
{
return -1;
}
strncpy( pPath, pathname, strlen( pathname ) + 2 );
// 补上结尾的 '/'
pPath[strlen(pPath)] = '/';
char*pPath2 = pPath;
if ( *pPath2 )
{
folders.push_back( pPath2++ );
}
while ( *pPath2 )
{
if ( *pPath2 == '/' )
{
*pPath2++ = '\0';
while ( *pPath2 == '/' )
{
*pPath2++ = '\0';
}
folders.push_back( pPath2++ );
}
else
{
pPath2++;
}
}
string s;
for ( int index = 0 ; index < folders.size() ; index++ )
{
s.append( folders[index] );
s.append( "/" );
if ( mkdir( s.c_str() , mode ) == -1 && errno != EEXIST )
{
cout << "error:" << strerror( errno ) << endl;
return -1;
}
}
delete pPath;
return 0;
}
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <vector>
using namespace std;
int Mkdir( const char *pathname, mode_t mode )
{
char* pPath = NULL;
vector< const char* > folders ;
if ( ( pPath = (char*)malloc( strlen( pathname ) + 2 ) ) == NULL )
{
return -1;
}
strncpy( pPath, pathname, strlen( pathname ) + 2 );
// 补上结尾的 '/'
pPath[strlen(pPath)] = '/';
char*pPath2 = pPath;
if ( *pPath2 )
{
folders.push_back( pPath2++ );
}
while ( *pPath2 )
{
if ( *pPath2 == '/' )
{
*pPath2++ = '\0';
while ( *pPath2 == '/' )
{
*pPath2++ = '\0';
}
folders.push_back( pPath2++ );
}
else
{
pPath2++;
}
}
string s;
for ( int index = 0 ; index < folders.size() ; index++ )
{
s.append( folders[index] );
s.append( "/" );
if ( mkdir( s.c_str() , mode ) == -1 && errno != EEXIST )
{
cout << "error:" << strerror( errno ) << endl;
return -1;
}
}
delete pPath;
return 0;
}
范晨鹏
------------------
软件是一种态度
成功是一种习惯
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步