본문 바로가기

Studies/Advanced Programming in the UNIX Environment

File mode checker

APUE 책에 IF - ELSE로 구현 된 것을 switch - case로 재구현 한 것. stat 스트럭쳐 의 st_mode 의 내부를 들여다 본 것.

헤더파일과 구현부로 나뉘어 있음.

 
/* Header : myhdr.h */

#include <sys/types.h>
#include <sys/stat.h>
#include "ourhdr.h"

//Defined Values
#define N_IFREG 32768 // 1000 0000 0000 0000
#define N_IFDIR 16384 // 0100 0000 0000 0000   
#define N_IFCHR 8192 // 0010 0000 0000 0000
#define N_IFBLK 24576 // 0110 0000 0000 0000
#define N_IFIFO 4096 // 0001 0000 0000 0000
#define N_IFLNK 40960 // 1010 0000 0000 0000
#define N_IFSOCK 49152 // 1100 0000 0000 0000
#define MASK 61440 // 1111 0000 0000 0000

/* End of myhdr.h */

/* Source : file_mode.c */

#include "myhdr.h"

int main(int argc, char *argv[])
{
    int  i; //for loop
    int   mode ; //mode checker by bits
    struct stat buf;
    char  *ptr;

    for (i = 1; i < argc; i++)
    {
        printf("%s: ", argv[i]);
        if (lstat(argv[i], &buf) < 0)
        {
            err_ret("lstat error");
            continue;
        }

        mode = buf.st_mode & MASK; //Masking

        switch (mode)
        {
            case N_IFREG :
                ptr = "regular";
            break;

            case N_IFDIR :
                ptr = "directory";
            break;

            case N_IFCHR :
                ptr = "character special";
            break;

            case N_IFBLK :
                ptr = "block special";
            break;

            case N_IFIFO :
                ptr = "fifo";
            break;

#ifdef S_IFLNK
            case N_IFLNK :
                ptr = "symbolic link";
            break;
#endif
#ifdef S_IFSOCK
            case N_IFSOCK :
                ptr = "socket";
            break;
#endif
            default :
                ptr = "** unknown mode **";
            break;    
        }//end of switch

        printf("%s\n", ptr);

    }//end of for

    exit(0);
}
/* End of file_mode.c */

'Studies > Advanced Programming in the UNIX Environment' 카테고리의 다른 글

myShell  (0) 2008.08.12
myCAT : cat(1)  (0) 2008.08.12
WC : Word Count  (0) 2008.08.10
실행파일 만들기 : Make a .exe file for APUE  (0) 2008.08.10
error.c  (0) 2008.08.10