Link to home
Start Free TrialLog in
Avatar of jewee
jewee

asked on

Create directory

I want to check if a directory exists (linux platform), then if it doesn't, I want to create a directory.

How do I check for a directory?

ALso, if the directory is the following: /tmp/sub1/process

and sub1 doesn't exist and process doesn't exist, how would I go about creating both?
Avatar of avizit
avizit

NAME
       opendir - open a directory

SYNOPSIS
       #include <sys/types.h>
       #include <dirent.h>EACCES Permission denied.
DIR *opendir(const char *name);

the possible error status are

       EMFILE Too many file descriptors in use by process.

       ENFILE Too many files are currently open in the system.

       ENOENT Directory does not exist, or name is an empty string.

       ENOMEM Insufficient memory to complete the operation.

       ENOTDIR         name is not a directory.



       


you would be interested in the  ENOENT condition which means the said directory doesnt exist.

/abhijit/

>>ALso, if the directory is the following: /tmp/sub1/process

>>and sub1 doesn't exist and process doesn't exist, how would I go about creating both?

just search for the exact match, if it is not then something is missing as required.then take a action to creat the exactly same.
try to thnk in this direction, i am sure u will find ur answer.

regards,
amit
ASKER CERTIFIED SOLUTION
Avatar of stefan73
stefan73
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Axter
Here's some portable code for checking directory existance:

#include <sys/stat.h>

bool FileExist(const char* FileName)
{
    struct stat my_stat;
    return (stat(FileName, &my_stat) == 0);
}

bool IsDirectory(const char* FileName)
{
    struct stat my_stat;
    if (stat(FileName, &my_stat) != 0) return false;
    return ((my_stat.st_mode & S_IFDIR) != 0);
}

int main(int argc, char* argv[])
{
    bool v1 = FileExist("c:\\autoexec.bat");
    bool v2 = FileExist("c:\\nofile.bat");
    bool v3 = FileExist("c:\\config.sys");
    bool v4 = FileExist("c:\\nofile2.bat");
    bool v5 = IsDirectory("c:\\windows");
    bool v6 = IsDirectory("c:\\notA_dir");
    bool v7 = IsDirectory("c:\\WINNT");
    return 0;
}
The above wrapper functions works on all major platforms.