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);

                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 –

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply