C++ loop to create multiple levels of directory and determine whether the directory exists

  • 2020-05-09 18:58:07
  • OfStack

C++ loops to create multiple levels of directories


#include "unitfiles.h" 
 
#ifdef WIN32 
 
#include <direct.h> 
#include <io.h> 
 
#elif LINUX 
 
#include <stdarg.h> 
#include <sys/stat.h> 
 
#endif 
 
#ifdef WIN32 
 
#define ACCESS _access 
#define MKDIR(a) _mkdir((a)) 
 
#elif LINUX 
 
#define ACCESS access 
#define MKDIR(a) mkdir((a),0755) 
 
#endif 
 
int CreatDir(char *pszDir) 
{ 
  int i = 0; 
  int iRet; 
  int iLen = strlen(pszDir); 
 
  // In the end / 
  if (pszDir[iLen - 1] != '\\' && pszDir[iLen - 1] != '/') 
  { 
    pszDir[iLen] = '/'; 
    pszDir[iLen + 1] = '\0'; 
  } 
 
  //  Create a directory  
  for (i = 0;i <= iLen;i ++) 
  { 
    if (pszDir[i] == '\\' || pszDir[i] == '/') 
    {  
      pszDir[i] = '\0'; 
 
      // If it doesn't exist , create  
      iRet = ACCESS(pszDir,0); 
      if (iRet != 0) 
      { 
        iRet = MKDIR(pszDir); 
        if (iRet != 0) 
        { 
          return -1; 
        }  
      } 
      // support linux, Will all \ Switch to / 
      pszDir[i] = '/'; 
    }  
  } 
  return 0; 
} 

It has been modified according to others' results. The problem to be noted is that the parameter is not const, so it can be modified.

  C++ determines whether the specified directory exists


bool IsDirExist(string filename) 
{ 
  size_t len = filename.length(); 
  if(filename[len-1] != '/' && filename[len-1] != '\\') 
    filename.append("/"); 
  filename.append("000.tmp"); 
  ofstream outf(filename.c_str()); 
  bool flag = outf; 
  if(outf) 
  { 
    outf.close(); 
    remove(filename.c_str()); 
  } 
  return flag; 
} 


Related articles: