#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
pathname : 정보를 알고자 하는 파일 명
statbuf : 검색한 파일 정보를 저장할 구조체 주소
성공시 : 0
실패시 : -1
파일 정보를 검색하는 데 가장 많이 사용하는 함수로, 파일을 읽으려 할 때 r/w/o 권한이 반드시 있어야 하는 것은 아니다. 하지만 파일에 이르는 경로의 각 디렉터리에 대한 읽기 권한은 필요하다.
stat 구조체의 세부 정보 - man -s 2 stat 명령어로 확인 가능하다.
예제
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(){
struct stat statbuf;
stat("linux.txt", &statbuf);
printf("Inode = %d\n",(int)statbuf.st_ino);
printf("Mode = %o\n",(unsigned int)statbuf.st_mode);
printf("Nlink = %o\n",(unsigned int) statbuf.st_nlink);
printf("UID = %d\n",(int)statbuf.st_uid);
printf("GID = %d\n",(int)statbuf.st_gid);
printf("SIZE = %d\n",(int)statbuf.st_size);
printf("Blksize = %d\n",(int)statbuf.st_blksize);
printf("Blocks = %d\n",(int)statbuf.st_blocks);
printf("** timespec Style\n");
printf("Atime = %d\n",(int)statbuf.st_atim.tv_sec);
printf("Mtime = %d\n",(int)statbuf.st_mtim.tv_sec);
printf("Ctime = %d\n",(int)statbuf.st_ctim.tv_sec);
printf("** old Style\n");
printf("Atime = %d\n",(int)statbuf.st_atime);
printf("Mtime = %d\n",(int)statbuf.st_mtime);
printf("Ctime = %d\n",(int)statbuf.st_ctime);
}
실행 결과
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int fstat(int fd, struct stat *statbuf);
fd : 열려 있는 파일의 기술자
statbuf : 검색한 파일 정보를 저장할 구조체 주소
성공시 : 0
실패시 : -1
예시
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
int fd;
struct stat statbuf;
fd=open("linux.txt", O_RDONLY);
if(fd==-1){
perror("open : linux.txt");
exit(1);
}
fstat(fd,&statbuf);
printf("Inode = %d\n",(int)statbuf.st_ino);
printf("UID = %d\n",(int)statbuf.st_uid);
close(fd);
}
실행 결과