james jung
james jung

Reputation: 21

c++ Checking if a directory exists in Unix and call void function if it exists.

So I'm trying to implement linux command rm -rf and in my main i have something like:

struct stat sb;
if(unlink(argv[i]) == 0)
{
    printf (argv[i]); printf(" Deleted\n");
}
if (S_ISDIR(sb.st_mode))
{   
    remove_dir(argv[i]);
}
else 
{
    perror(argv[i]);
}

What I am trying to do is that if the user input is directory, then call the void remove_dir(); to delete the directories, but instead it just prints whether argv[i] is directories or not. Any suggestions would be very helpful.

Upvotes: 0

Views: 69

Answers (1)

Jonas
Jonas

Reputation: 7017

You need to populate struct stat sb using the function stat:

struct stat sb;
if (stat(argv[i], &sb) != 0) 
{
    perror(argv[i]);
}

Then, and only then, can you use S_ISDIR(sb.st_mode).

Upvotes: 1

Related Questions