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;
}
原文地址:https://www.cnblogs.com/diylab/p/1447796.html