Make Sure Path Exists

-->

Environment: not specified

An alternative way to the API MakeSureDirectoryPathExists function.

Introduction

Sure, you can use the API version of MakeSureDirectoryPathExists function to satisfy your needs, but there must be an alternative way. What do you need to do if you want to use the API MakeSureDirectoryPathExists function?

First, you have to include 'imagehlp.h' into your project file and point to the 'imagehlp.lib' file so you can link to it. The result is that you will never know how an API function is implemented. Additionally, the size of your released executable file that uses it will blow up.

I dare to present my two versions of a functions to perform the same task as MakeSureDirectoryPathExists does. The main purpose any of them is to make sure the required path exists. If it doesn't, the function creates the nessesary folders to fit the requested path. These functions are not recursive -- they are fast, small and universal.

How Does It Work?

Both versions works as the API MakeSureDirectoryPathExists function but a little bit occuratly. Note the second parameter of each function. It tells a function whether a filename is included to the path or isn't. It is necessary because you may create a file without an extension and thus there is no way to determine is there a folder name or a filename without an extension. The same, you may create a folder with an extension and here we go again, there is no way to determine is there a filename or a folder name with an extension. Only you can tell a function the way it has to work. When you provide a path a function does not care if there any trailing slash or back slash presents. The difference between the MFC version and the "C" version is that "C" version is a little bit faster, requires no additional memory usage and cares both the slash and the back slash symbols. You can pass CString object to the "C" version fuction and that's ok.

BOOL MakeSurePathExists( CString &Path, 
                         bool FilenameIncluded=true)
{
   int Pos=0;
   while((Pos=Path.Find('\\',Pos+1))!=-1) 
      CreateDirectory(Path.Left(Pos),NULL);
   if(!FilenameIncluded)
      CreateDirectory(Path,NULL);
   return ((!FilenameIncluded)?!_access(Path,0):
        !_access(Path.Left(Path.ReverseFind('\\')),0));
}

int make_sure_path_exists( const char *iPath, 
                           bool FilenameIncluded=true)
{
   char *Path=(char*)iPath, 
        *TmpPath=Path, 
        TmpSmb=0,
        *LastDPtr=NULL;
   while((TmpPath=strpbrk(TmpPath+1,"\\/")))
   {
      TmpSmb=Path[TmpPath-Path];
      Path[TmpPath-Path]=0;
      CreateDirectory(Path,NULL);
      Path[TmpPath-Path]=TmpSmb;
      LastDPtr=TmpPath;
   }

   int Res=1;
   if(!FilenameIncluded)
   {
      CreateDirectory(iPath,NULL);
      Res=!_access(iPath,0);
   }
   else
   {
      if(LastDPtr)
      {
         Path=(char*)iPath;
         TmpSmb=Path[LastDPtr-Path];
         Path[LastDPtr-Path]=0;
         Res=!_access(Path,0);
         Path[LastDPtr-Path]=TmpSmb;
      }
   }
   
   return Res;
}


Comments

  • the cheapest clarisonic pro with consistency scrub sale in the ebay

    Posted by iouwanzi on 06/06/2013 06:51pm

    [url=http://www.miaclarisonicaustralia.org/]clarisonic mia australia[/url] Notre coiffeur étranger encouragés plus tôt ghd Gold styler à mon avis, ainsi que maintenant nos U. s. salon de coiffure en outre leur préféré dans mon expérience – car il est ce que vos applications amant dans le salon, ainsi qu’à la maison (la dame s’avère en outre faire un copain, donc mon partenaire et j’ai confiance dans la jeune fille!). Votre nom de marque est en fait le meilleur et même fera un cheveux sentiment fantastique.Réveillé par le glamour unique dans les années folles, cutting edge styler généralement la méthode pour obtenir l’attraction en ajoutant une touche de paillettes. Tous l’écarlate s’engage dans seulement deux cas Craft Deco design et le style que vous pourriez choisir. [url=http://www.australiaclarisonic.com/]clarisonic mia[/url] modestes caractéristiques consistent non pas un mais deux défini guides mise en page talents Deco, simultanément disponible ce sont unique. Toute la galerie Scarlet comprend un sac soie cramoisi tolérant à chaleur merveilleuse lesoù aider à stocker le fer à lisser vos plaques ghd IV Styler cheveux pour s’assurer vous rose profond, par le biais de non pas un mais deux trucs cheveux sauvages dont une instance appropriée.Écrit à l’intérieur d’une boîte commune inflammed inanité habilitée par période de Style déco, tous le groupe écarlate fantaisie ghd styler intemporelle métal jaune comprend une alimentation réduite option rouge et en outre une mallette de rangement, un voyage fabuleux crinière sèche-cheveux ghd, couple de crinière de films et en outre un important carton satiné résistant à la chaleur. [url=http://www.australiaclarisonic.com/clarisonic-mia]clarisonic mia[/url] Ce redressement en termes de fer relèvent de 4 modèles. Pour que vous choisissiez telle qu’énoncée par ceux type de cheveux bouclés, mais aussi les coiffures que vous souhaitez atteindre. Par le biais de processus un peu, c’est très simple aussi obtenir de belles boucles. Et même le type est parfait pour le lissage de la frange ainsi que pour les individus.Espagne, GHD annonce une promotion très utile. Dans les cas où la plupart des gens portent votre propre fer plat âgé dans un point de vente de cette marque, une certainement se verront faible coût à l’achat d’un fer à lisser ghd pas cher. Il est généralement valable jusqu’au 6 mai 2011. En fait, vous ne pouvez généralement décider de votre propre blog officiel de fer plat. Certaines personnes offrent le monde entier !Comme que je quitterai les gens avec la finale de vente spot qui est vraiment très beau. Une Cendrillon moderne important !

    Reply
  • Isn't BOB a weenie?!?

    Posted by Legacy on 04/01/2003 12:00am

    Originally posted by: joe

    He doesn't do anything useful or have any original thoughts, so he just goes around knocking other's efforts.
    You suck BOB!

    Reply
  • Thanks

    Posted by Legacy on 03/31/2003 12:00am

    Originally posted by: Nosser

    Just what I was looking for...

    ps. I noticed lots of comments on this codesnip misstaking it as a check for filepath existence... Must have been frustrating :P

    Reply
  • Cool down - btw nice code

    Posted by Legacy on 10/31/2002 12:00am

    Originally posted by: Teddy

    You made a nice code, Boy. Change your tune (R U some Russian?) nobody is against you. Those are visiting this site are not idiots beleive me, are they? So do not put capitals and comments on people who made some comment on your code and not on you. It is not a personal attack.
    Good job however with some small missing items.

    Reply
  • An API exists for this job

    Posted by Legacy on 10/08/2002 12:00am

    Originally posted by: BOB

    The API

    BOOL PathFileExists(
    LPCTSTR pszPath
    );

    Already does this. It is from shlwapi.lib

    Reply
  • FindFirstFile network access problem

    Posted by Legacy on 09/10/2002 12:00am

    Originally posted by: Dennis

    Hi,

    I wrote a C++ console code to parse a network
    directory as follow :

    FILETIME filet;
    const HANDLE InvHndVal = INVALID_HANDLE_VALUE;
    HANDLE FndHnd;
    WIN32_FIND_DATA FndInf;
    BOOL FndFlg;
    long maxtime = 0;
    char* fDir = "\\\computerA\\Dir1\\Dir2\\";

    FndHnd = FindFirstFile(fDir, FndInf);
    FndFlg = FndHnd != InvHndVal;
    while (FndFlg) // While a file has be found.
    {
    strcat(fDir,FndInf.cFileName);
    filet.dwHighDateTime =
    FndInf.ftLastWriteTime.dwHighDateTime;
    if(maxtime < filet.dwHighDateTime)
    {
    maxtime = filet.dwHighDateTime;
    memset(fname, '\0', 72);
    strcpy(fname, FndInf.cFileName);
    }
    FndFlg = FindNextFile(FndHnd,&FndInf);
    }
    FindClose(FndHnd);

    and I encountered with problem at this line:

    FndHnd = FindFirstFile(fDir, FndInf);

    it seems like it could not recognize the network
    directory eventhough I already shared those
    directories.

    Did I miss something? Please enlighten me

    Thanks in advance

    Dennis

    Reply
  • I respect your codes anyway...

    Posted by Legacy on 05/08/2002 12:00am

    Originally posted by: Joery Wen

    yeah, good job!

    really take us lots of time and something else, for examples, eyesight, to explore the way we need in MSDN or somewhere else, for example, on the Internet.

    Thus I sincerely respect your work. I just have written a little piece of codes doing nearly the same thing before I remember to find more here...//faint. It took me some time. and really take me some eyesight,hehe.

    really good job!

    keep doing!

    Reply
  • An easier way

    Posted by Legacy on 03/16/2002 12:00am

    Originally posted by: rod

    BOOL Exist(const CString& sFilespec)
    
    {
    WIN32_FIND_DATA fd;

    HANDLE hFind = FindFirstFile(sFilespec, &fd);

    if (hFind == INVALID_HANDLE_VALUE)
    {
    FindClose(hFind);
    return FALSE;
    }

    FindClose(hFind);
    return TRUE;
    }

    Example:

    if ( Exist("c:\\windows\\*.*"))
    {

    }

    Reply
  • I Forgot To Say...

    Posted by Legacy on 03/15/2002 12:00am

    Originally posted by: Arlen Albert Keshabian

    To use _access function you must include <io.h> header file.
    In some cases in order to use strpbrk function you must include <string.h> header file.

    Best wishes and regards,
    Arlen.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds