Question

I want to check and then create a dir if it does not already exists.

I used the following code:

#define APP_DATA_DIR_CHILD_2  "./child2"

g_nResult = GetFileAttributes((wchar_t*)APP_DATA_DIR_CHILD_2);
if (g_nResult <= 0)
{
    g_nResult = mkdir(APP_DATA_DIR_CHILD_2);
}

But is is not checking properly. I get -1 returned in GetFileAttributes() even after the directory has been created.

Could someone please help?

PS: I would also like to make sure that the code works on both Linux and Windows.

Was it helpful?

Solution

Replace

#define APP_DATA_DIR_CHILD_2                    "./child2"
g_nResult = GetFileAttributes((wchar_t*)APP_DATA_DIR_CHILD_2);

By (if Unicode is defined)

#define APP_DATA_DIR_CHILD_2                    L"./child2"
g_nResult = GetFileAttributes(APP_DATA_DIR_CHILD_2);

Your code is far away of portable... Use stat instead

struct stat sts;
if ( stat(APP_DATA_DIR_CHILD_2, &sts) != 0) {
    // Fail to get info about the file, may not exist...
}
else {
    if (S_ISDIR(sts.st_mode)) {  /* The file is a directory... */ }
}

Take a look at the documentation : http://linux.die.net/man/2/stat

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top