manintheBottle
manintheBottle

Reputation: 35

How to know a file's type?

I have to code a function of type char that returns the type of a file. I'm given the clue of using mode_t, but don't know really how to do it.

I've been searching, and I've seen answers in other languages, but not in C.

The output is expected to be a char, indicating the file type. Any clue on how to do it? Is it any function I should use?

Upvotes: 0

Views: 296

Answers (1)

Israel Figueirido
Israel Figueirido

Reputation: 350

Maybe this helps, it should work.

char FileType (mode_t m) {
    switch (m & S_IFMT) {               //bitwise AND to determine file type
        case S_IFSOCK:  return 's';     //socket
        case S_IFLNK:   return 'l';     //symbolic link
        case S_IFREG:   return '-';     //regular file
        case S_IFBLK:   return 'b';     //block device
        case S_IFDIR:   return 'd';     //directory
        case S_IFCHR:   return 'c';     //char device
        case S_IFIFO:   return 'p';     //pipe
        default: return '?';            //unknown
    }
}

S_IFMT is a bit mask for file type (see man stat).

Upvotes: 3

Related Questions