Thread: Directory Existance

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    2

    Directory Existance

    Hi, I'm struggling with how to check to see if the users computer has a certain directory. What i'm doing is making the directory, but I don't want to do it if it already exists. The way I'm making it is below :

    // define variables :
    string path = "\\testingdir";
    string command_mkdir = "mkdir " + path;

    // make the directory :
    system(command_mkdir.c_str());

    I want to put the bottom line in an "if statement", so it only makes the directory if it doesn't exist. Can someone please give me a little help?

    brad

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Try this:
    Code:
    #include <io.h>
    
    bool file_exists(char *filename);
    
    int main(void)
    {
       char filename[81] = "file.txt";
       if (!file_exists(filename))
          cout << "File " << filename << " not found.\n";
       return 0;
    }
    
    bool file_exists(char *filename)
    {
       if (access(filename,0) == 0)
          return true;
       return false;
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    I assume this is an MS operating system, with those \\ chars

    This is one way.
    Every directory has a pseudo file called nul in it (which you cant see, but it's there)

    Code:
    int main ( ) {
      FILE *fp = fopen( "foo\\nul", "r" );
      if ( fp ) {
        fclose( fp );
        printf( "Yes\n" );
      } else {
        printf( "No\n" );
      }
      return 0;
    }
    Basically, if the nul file exists, so does the directory

    You could also use the stat() function if your compiler supports it, or maybe even the findfirst() DOS/windows function

  4. #4
    Registered User
    Join Date
    Feb 2002
    Posts
    2

    Smile Thanks Salem

    Thanks Salem, I had no idea there was a null file in every directory. That works perfectly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  2. Couple errors please help :-D
    By JJJIrish05 in forum C Programming
    Replies: 9
    Last Post: 03-06-2008, 02:54 AM
  3. Replies: 6
    Last Post: 07-30-2003, 03:08 AM
  4. Directory reading trouble
    By samGwilliam in forum Linux Programming
    Replies: 0
    Last Post: 03-10-2002, 09:43 AM
  5. The Site Directory
    By kermi3 in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-22-2002, 08:19 PM