Identify / Test file types in Linux using C program stat API

The file mode, stored in the st_mode field of the file attributes, contains two kinds of information: the file type code, and the access permission bits. This section discusses only the type code, which you can use to tell whether the file is a directory, socket, symbolic link, and so on.

There are two ways you can access the file type information in a file mode. Firstly, for each file type there is a predicate macro which examines a given file mode and returns whether it is of that type or not. Secondly, you can mask out the rest of the file mode to leave just the file type code, and compare this against constants for each of the supported file types.

All of the symbols listed in this section are defined in the header file sys/stat.h.

 $ vim know_file_type_using_stat.c 
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char **argv) {
        struct stat *st;
        st = (struct stat *) malloc(sizeof(struct stat));
 
        stat(argv[1], st);
 
        if(S_ISDIR(st->st_mode))
                printf("file type is : Directory\n");
        else if (S_ISCHR(st->st_mode))
                printf("file type is : Character device\n");
        else if (S_ISBLK(st->st_mode))
                printf("file type is : Block device\n");
        else if (S_ISREG(st->st_mode))
                printf("file type is : Regular file\n");
        else if (S_ISFIFO(st->st_mode))
                printf("file type is : FIFO or Pipe\n");
        else if (S_ISLNK(st->st_mode))
                printf("file type is : Symbolic link\n");
        else if (S_ISSOCK(st->st_mode))
                printf("file type is : Socket\n");
        return 0;
}
 $ gcc -o know_file_type_using_stat know_file_type_using_stat.c 
$ ./know_file_type_using_stat helloworld.txt 
file type is : Regular file 
$ ./know_file_type_using_stat /dev/tty0
file type is : Character device 
$ ./know_file_type_using_stat /dev/sda1
file type is : Block device 
$ ./know_file_type_using_stat $PWD
file type is : Directory

Reference – https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html

Leave a Comment