CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 1999
    Posts
    40

    io.h and _access

    Is there a standard C or standard C++ function for the _access in io.h for
    seeing if a file or directory exists?
    LP

    Lorn "ljp" Potter
    Trolltech Qtopia Community Liaison
    irc.freenode.net #qtopia, #qt

  2. #2
    Join Date
    May 1999
    Location
    Netherlands
    Posts
    57

    Re: io.h and _access

    You can use:

    int file_exists(char *file)
    { /* Check for existence */
    if( (_access( file, 0 )) != -1 )
    {
    return true;
    }
    return false;
    }




    From my code (works always):

    int file_exists(char *file)
    {
    FILE *fd;

    if(strlen(file)==0)
    {
    /* No legal file name */
    return false;
    }
    if((fd=fopen(file,"r"))==NULL)
    {
    /* File doesn't exists */
    return false;
    }
    /* File exists */
    fclose(fd);
    return true;
    }

    int dir_exists(char *directory_path)
    {
    char current_path[MAX_PATH+1];

    /* Store current working directory */
    if(_getcwd(current_path,MAX_PATH)==NULL)
    {
    /* Action failed */
    return false;
    }

    if(_chdir(directory_path)==-1)
    {
    /* Directory doesn't exists */
    return false;
    }
    /* Directory exists, go back to old directory */
    if(_chdir(current_path)==-1)
    {
    /* Can't go back to current directory */
    return false;
    }
    return true;
    }




    Mark


  3. #3
    Join Date
    Jun 1999
    Location
    Miami, FL
    Posts
    972

    Re: io.h and _access

    The function I use is "stat". Here's how I use it:


    // Returns true if the given szPath is a valid directory.
    bool IsDir(const char* szPath)
    {
    assert(szPath);

    struct stat statBuffer;
    return (stat(szPath, &statBuffer) >= 0 && // make sure it exists
    statBuffer.st_mode & S_IFDIR); // and it's not a file
    }

    // Returns true if the given szFile a valid file.
    bool IsFile(const char* szFile)
    {
    assert(szFile);

    struct stat statBuffer;
    return (stat(szFile, &statBuffer) >= 0 && // make sure it exists
    statBuffer.st_mode & S_IFREG); // and it's not a directory
    }





Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured