• 正文
  • 相关推荐
申请入驻 产业图谱

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

12/11 13:36
237
加入交流群
扫码加入
获取工程师必备礼包
参与热点资讯讨论

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: %sn", 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: %ldn", (long)file_info.st_ino);

printf("File size: %ld bytesn", (long)file_info.st_size);

// (2) 判断文件的其他用户权限

printf("Readable by others: %sn", (file_info.st_mode & S_IROTH) ? "Yes" : "No");

printf("Writable by others: %sn", (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

相关推荐