# Directory Existance

This is a discussion on Directory Existance within the C++ Programming forums, part of the General Programming Boards category; Hi, I'm struggling with how to check to see if the users computer has a certain directory. What i'm doing ...

1. ## 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?

2. Try this:
Code:
#include <io.h>

bool file_exists(char *filename);

int main(void)
{
char filename[81] = "file.txt";
if (!file_exists(filename))
return 0;
}

bool file_exists(char *filename)
{
if (access(filename,0) == 0)
return true;
return false;
}

3. 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. ## Thanks Salem

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