Linux獲取檔案屬性stat()、fstat()、lstat()函式例項學習
阿新 • • 發佈:2019-01-02
/* file stat example */ #include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <stdlib.h> #include <time.h> int main(int argc, char **argv){ struct stat st; if(argc != 2){ fprintf(stderr, "Usage: %s <file_pathname> \n", argv[0]); exit(EXIT_FAILURE); } if(stat(argv[1], &st) == -1){ perror("stat"); exit(EXIT_SUCCESS); } printf("File type: "); switch(st.st_mode & S_IFMT){ case S_IFBLK: printf("block device\n"); break; case S_IFCHR: printf("character device\n"); break; case S_IFDIR: printf("directory\n"); break; case S_IFIFO: printf("FIFO/pipe\n"); break; case S_IFLNK: printf("symlink\n"); break; case S_IFREG: printf("regular file\n"); break; case S_IFSOCK: printf("socket\n"); break; default: printf("unknown?\n"); break; } printf("I-node number: %ld\n", (long) st.st_ino); printf("Mode: %lo (octal)\n", (unsigned long) st.st_mode); printf("Link count: %ld\n", (long) st.st_nlink); printf("Ownership: UID=%ld GID=%ld\n", (long) st.st_uid, (long) st.st_gid); printf("device containing file id:%ld \n", (long) st.st_dev); printf("device id: %ld \n", (long) st.st_rdev); printf("File size: %lld bytes\n", (long long) st.st_size); printf("Preferred I/O block size: %ld bytes\n", (long) st.st_blksize); printf("Blocks allocated: %lld\n", (long long) st.st_blocks); printf("Last status change: %s", ctime(&st.st_ctime)); printf("Last file access: %s", ctime(&st.st_atime)); printf("Last file modification: %s", ctime(&st.st_mtime)); exit(EXIT_SUCCESS); }
五、執行測試效果