news 2026/4/21 7:07:20

飞凌嵌入式ElfBoard-获取文件的状态信息之fstat

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
飞凌嵌入式ElfBoard-获取文件的状态信息之fstat

fstat函数用来获取已经打开的文件描述符相关的文件状态信息。

1.头文件

#include <sys/stat.h>

2.函数原型

int fstat(int fd, struct stat *statbuf);

3.参数

fd:文件描述符,表示已打开的文件。

statbuf:指向 struct stat 结构的指针,用于存储文件的状态信息。

4.返回值

若成功返回0,失败返回-1

5.示例:(使用fstat获取文件状态信息

#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;

6.测试结果

Inode number: 5255757

File size: 17 bytes

Readable by others: Yes

Writable by others: No

Last access time: 2024-08-09 14:12:11

Last modification time: 2024-08-09 14:12:11

Last status change time: 2024-08-09 14:12:11

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!