#include <sys/stat.h>
int stat(const char *pathname, struct stat *buf); //FILE 경로이용
int fstat(int filedes, struct stat *buf); //OPEN된 파일 이용
int lstat(const char *pathname, struct stat *buf); //SYSBOLIC LINK
//성공시 0, 실패시 -1 반환.
struct stat {
mode_t st_mode; //파일의 타입과 권한
ino_t st_ino; // i-node number (serial number)
dev_t st_dev; // device number (file system)
dev_t st_rdev; /* device number for special files */
nlink_t st_nlink; /* number of links */
uid_t st_uid; // user ID of owner
gid_t st_gid; // group ID of owner
off_t st_size; // file의 byte 크기
time_t st_atime; // 최근에 접근한 시간
time_t st_mtime; // 최근에 변경된 시간
time_t st_ctime; //마지막으로 status가 변경된 시간
blksize_t st_blksize; /* best I/O block size */
blkcnt_t st_blocks; /* number of disk blocks allocated */
};
📗 예시 - 파일의 정보를 출력
#include <stdio.h>
#include <sys/stat.h>
/* 허가 비트가 설정되어 있는지 결정하기 위해 octarray를 사용 * /
static short octarray[9] = { 0400, 0200, 0100, 0040, 0020, 0010, 0004, 0002, 0001};
/* 화일 허가에 대한 기호화 코드 끝부분의 null 때문에 길이가 10문자이다. */
static char perms[10] = "rwxrwxrwx";
int filedata (const char *pathname)
{
struct stat statbuf; // file의 정보를 닮을 인자
char descrip[10]; //출력할 값
int j:
//두번째인자인 statbuf에 pathname에 해당하는 파일의 정보가 담긴다.
if(stat (pathname, &statbuf) == -1)
{
fprintf (stderr, "Couldn't stat %s\n", pathname);
return (-1);
}
/* 허가를 읽기 가능한 형태로 바꾼다. */
for( j = 0; j < 9; j++)
{
/ * 비트별 AND를 사용하여 허가가 설정되었는지 테스트 */
if (statbuf.st_mode & octarray[j])
descrip[j] = perms[j];
else
descrip[j] = '-';
}
descrip[9] = '\0'; /* 하나의 문자열을 가지도록 확인 */
/* 화일 정보를 출력한다. */
printf ("\nFile %s :\n", pathname);
printf ("Size %ld bytes\n", statbuf.st_size);
printf ("User-id %d, Group-id %d\n\n", statbuf.st_uid, statbuf.st_gid);
printf ("Permissions: %s\n", descrip);
return (0);
}