# C++ Check If Folder Exists (Windows)



## AMD+nVidia

Ok I've looked and looked on Google and I just can't figure this out guys. I'm trying to run a check to see if a folder exists in windows based on a string input.

There seems to be no easy way to do this! Anybody got a simple way?


----------



## Dobbie

Just use a try catch.


----------



## DuckieHo

Isn't there a function that does that?


----------



## godsgift2dagame

Well, to check, you could set up a function that creates the folder if and only if it doesn't already exist.

Code:



Code:


#include <windows.h>
#include <iostream>

CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

void CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs)
{
       if(!CreateDirectory("c:\\\\mydir", NULL)) 
           std::cout << "Creating failed"; 
       else
           std::cout << "Success!";
}


----------



## AMD+nVidia

Quote:


Originally Posted by *godsgift2dagame* 
Well, to check, you could set up a function that creates the folder if and only if it doesn't already exist.

Code:



Code:


#include <windows.h>
#include <iostream>

CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

void CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs)
{
       if(!CreateDirectory("c:\\\\mydir", NULL)) 
           std::cout << "Creating failed"; 
       else
           std::cout << "Success!";
}


This looks like exactly what I want, I will try it now


----------



## godsgift2dagame

_It work?_


----------



## AMD+nVidia

Sorry I'm just not smart enough to do this, I'm scrapping the project


----------



## godsgift2dagame

Quote:


Originally Posted by *AMD+nVidia* 
Sorry I'm just not smart enough to do this, I'm scrapping the project









Show the code...someone might be able to help, bud.


----------



## AMD+nVidia

Quote:


Originally Posted by *godsgift2dagame* 
Show the code...someone might be able to help, bud.

Nah, I have to look up every line and thing.

This was just supposed to be a fun project, I need to learn more first


----------



## Nakurusin

Well I know you've somewhat given up, but for others who read it or perhaps yourself in future... If using the Windows API, there are usually a few ways to check, personally as a quick fix way I use GetFileAttributes() which can be used on a folder directory aswell as an actual file.

Example:

Code:



Code:


if ((GetFileAttributes(cLocati.c_str())) == INVALID_FILE_ATTRIBUTES)
{
cout << "Directory doesn't exist\
";
CreateDirectory(cLocati.c_str(), 0);
cout << "Directory Created\
";
}

What that does is it looks to get the Attributes for cLocati (which is of type std::string) that string is a location for a folder, not a file, when the folder does not exist, GetFileAttributes returns INVALID_FILE_ATTRIBUTES, as it can't gather any attributes, this indicates whether or not the folder exists, if that is the case, it executes the code in the brackets & proceeds to create the directory.

I will note there maybe a better way, I wrote that little part of code very quickly when testing something later in my code & I realised that a big error occured whenever the directory didn't exist, so wrote that as a quick fix temporarily, but I don't see why it can't be adapted somewhat.

http://msdn.microsoft.com/en-us/libr...44(VS.85).aspx


----------



## error10

If you want portable code, use stat(). (C function)

Code:



Code:


#include <sys/stat.h>

bool file_exists(string filename) {
    struct stat fileinfo;

    return !stat(filename.c_str(), &fileinfo);
}


----------



## Nakurusin

Quote:


Originally Posted by *error10* 
If you want portable code, use stat(). (C function)

Code:



Code:


#include <sys/stat.h>

bool file_exists(string filename) {
    struct stat fileinfo;

    return !stat(filename.c_str(), &fileinfo);
}


I would like to add however that while sys/stat.h is more cross-platform portable it is also non-standard C/C++ like the Windows API.

@error10: I'm just posting this while quoting you to add onto your post for clarity, as some may assume because it is portable that it is standard.


----------



## error10

Quote:


Originally Posted by *Nakurusin* 
I would like to add however that while sys/stat.h is more cross-platform portable it is also non-standard C/C++ like the Windows API.

@error10: I'm just posting this while quoting you to add onto your post for clarity, as some may assume because it is portable that it is standard.

The great thing about standards is that there are so many to choose from. stat() conforms to POSIX.1-2001


----------



## Nakurusin

Which is basically a Linux API standard as opposed to a C/C++ standard. Although your point is that is conforms to a standard which it does, you have your point.


----------



## error10

Quote:


Originally Posted by *Nakurusin* 
Which is basically a Linux API standard as opposed to a C/C++ standard. Although your point is that is conforms to a standard which it does, you have your point.

Yes, and Windows also supports POSIX. At least that POSIX standard. Again, there are so many to choose from.









Point being, if I wrote a Win32 call instead of a portable call, when I could have easily used the portable call, I'm setting myself up for either a maintenance nightmare later, when I have to change it anyway, or just getting fired.


----------



## Nakurusin

Quote:


Originally Posted by *error10* 
Yes, and Windows also supports POSIX. At least that POSIX standard. Again, there are so many to choose from.









Point being, if I wrote a Win32 call instead of a portable call, when I could have easily used the portable call, I'm setting myself up for either a maintenance nightmare later, when I have to change it anyway, or just getting fired.

Microsoft doesn't have POSIX support since Windows XP. They didn't include the subsystem with XP nor later versions. (Although you can add limited compliance, some Windows versions have limited compliance included)

It really depends on your target platform, if you're cross-platform then sure I agree, but alot of programs are targeted at a single platform more often than not & at those times the Windows API or POSIX, etc. will be available for use.

This is pointless to argue about though!







We both know both sets of code work, we both know they aren't part of the C++ standard (even if you can choose another standard to conform too, I'm not being purist, I'm just adding information, which in essence is the biggest benefit of this conversation) & I haven't yet disputed the portability of sys/stat.h over WinAPI as I know it is indeed more portable, I just wanted to add that neither code is part of the C++ standard for those users who are newer to C++ is all.


----------



## error10

Well, here's a pure C++ version, which as far as I know is completely standard.

Code:



Code:


#include <iostream>
#include <fstream>
using namespace std;

bool file_exists(string filename) {
    ifstream f(filename.c_str(), ifstream::in);
    return !f.fail(); // using good() could fail on empty files
}


----------



## Nakurusin

Quote:


Originally Posted by *error10* 
Well, here's a pure C++ version, which as far as I know is completely standard.

Code:



Code:


#include <iostream>
#include <fstream>
using namespace std;

bool file_exists(string filename) {
    ifstream f(filename.c_str(), ifstream::in);
    return !f.fail(); // using good() could fail on empty files
}


It is indeed, although it will only work with files not directories like stat() or GetFileAttributes(). Atleast in Windows, perhaps it works just fine with Linux directories.

There is as far as I'm aware no standard way to check if a directory exists, you have to use some non-standard or platform specific functions.


----------



## error10

Tested it and it works fine here. If it doesn't work on directories in Windows, then Windows is probably broken.









I think the take-away here is that portability is harder than it looks.


----------



## newbie1911

Code:



Code:


#include <iostream>
#include <fstream>
using namespace std;

bool file_exists(string filename) {
    ifstream f(filename.c_str(), ifstream::in);
    return !f.fail(); // using good() could fail on empty files
}
int main()
{
cout << file_exists("C:\\ATI") << endl;
getchar();
return 0;
}

always returns 0 even with non-existent file/folder names.


----------



## error10

Did you put in two backslashes?


----------



## newbie1911

yep, and it still returns 0.


----------



## Nakurusin

Quote:


Originally Posted by *newbie1911* 

Code:



Code:


#include <iostream>
#include <fstream>
using namespace std;

bool file_exists(string filename) {
    ifstream f(filename.c_str(), ifstream::in);
    return !f.fail(); // using good() could fail on empty files
}
int main()
{
cout << file_exists("C:\\ATI") << endl;
getchar();
return 0;
}

always returns 0 even with non-existent file/folder names.

The code works with files but not directories, add an ATI folder in C:\\ & add a text file like "test.txt" then try it with C:/ATI/test.txt & it should return 1 instead. Since we have spoken about some portability it is a good tip that with directories, it's best to use / as it doesn't require the escape character of \\ & since / works with Windows & Linux it is far more portable.


----------



## error10

I had to go and hunt down the actual C++ specification (ISO/IEC 14882:2003) and they want 380 Swiss francs for it! So I looked at a draft. It mentions absolutely nothing about directories in this context. So, since some operating systems treat files and directories differently *cough*Windows*cough* I guess there's probably no portable way to do it. At least not in C++.

Now, Visual C++ does have the C stat() call. I'm not sure who said it didn't. It's got a few minor quirks (e.g. you have to remove any trailing backslash from a directory pathname) but it should be serviceable.


----------



## Nakurusin

Quote:


Originally Posted by *error10* 
I had to go and hunt down the actual C++ specification (ISO/IEC 14882:2003) and they want 380 Swiss francs for it! So I looked at a draft. It mentions absolutely nothing about directories in this context. So, since some operating systems treat files and directories differently *cough*Windows*cough* I guess there's probably no portable way to do it. At least not in C++.

Now, Visual C++ does have the C stat() call. I'm not sure who said it didn't. It's got a few minor quirks (e.g. you have to remove any trailing backslash from a directory pathname) but it should be serviceable.

As you've figured, C++ has no standard for directory support & so on, it's left in the hands of the OS, if there were a standard way, I imagine we'll have both likely pointed it out by now.

Well no one in this thread has said Visual C++ doesn't have stat() as far as I'm aware, I've already stated I've used stat() in the past aswell (I might have erased that as it were already implied, but can't remember) I still think overall the best 2 options have been mentioned here.


----------



## AMD+nVidia

Why does EVERY ONE of my threads end up as a flamewar?!


----------



## Nakurusin

Quote:


Originally Posted by *AMD+nVidia* 
Why does EVERY ONE of my threads end up as a flamewar?!









This is a flamewar? =\\ To me it's been more like friendly discussion on the language, it's been informative & not really hostile to which would make it a flamewar.


----------



## Spotswood

Code:



Code:


bool DirectoryExists(LPCTSTR directoryName)
{
    DWORD attributes = GetFileAttributes(directoryName);
    if (attributes != INVALID_FILE_ATTRIBUTES[B] && 
        attributes & FILE_ATTRIBUTE_DIRECTORY[/B])
        return true;

    return false;
}


----------



## error10

Quote:


Originally Posted by *AMD+nVidia* 
Why does EVERY ONE of my threads end up as a flamewar?!









What flamewar?


----------

