Checking if a file is a directory or just a file.

Posted by Jookia on Stack Overflow See other posts from Stack Overflow or by Jookia
Published on 2010-12-29T09:45:44Z Indexed on 2010/12/29 9:54 UTC
Read the original article Hit count: 210

Filed under:
|

I'm writing a program to check if something is a file or is a directory. Is there a better way to do it than this?

#include <stdio.h>

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

int isFile(const char* name)
{
    DIR* directory = opendir(name);

    if(directory != NULL)
    {
     closedir(directory);
     return 0;
    }

    if(errno == ENOTDIR)
    {
     return 1;
    }

    return -1;
}

int main(void)
{
    const char* file = "./testFile";
    const char* directory = "./";

    printf("Is %s a file? %s.\n", file,
     ((isFile(file) == 1) ? "Yes" : "No"));

    printf("Is %s a directory? %s.\n", directory,
     ((isFile(directory) == 0) ? "Yes" : "No"));

    return 0;
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about posix