#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
void print_time(const char *label, time_t time) {
struct tm *tm_info;
char buffer[26];
tm_info = localtime(&time);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info);
printf("%s: %s\n", label, buffer);
}
int main() {
int fd = open("example.txt", O_RDONLY); // 打开文件,获取文件描述符
if (fd < 0) {
perror("open");
return 1;
}
struct stat file_info;
if (fstat(fd, &file_info) < 0) { // 使用 fstat 获取文件状态信息
perror("fstat");
close(fd);
return 1;
}
// (1) 获取文件的 inode 节点编号和文件大小
printf("Inode number: %ld\n", (long)file_info.st_ino);
printf("File size: %ld bytes\n", (long)file_info.st_size);
// (2) 判断文件的其他用户权限
printf("Readable by others: %s\n", (file_info.st_mode & S_IROTH) ? "Yes" : "No");
printf("Writable by others: %s\n", (file_info.st_mode & S_IWOTH) ? "Yes" : "No");
// (3) 获取文件的时间属性
print_time("Last access time", file_info.st_atime);
print_time("Last modification time", file_info.st_mtime);
print_time("Last status change time", file_info.st_ctime);
close(fd); // 关闭文件描述符
return 0;
}