ARM技术论坛
直播中

嵌入式小能手

2年用户 1514经验值
擅长:嵌入式技术
私信 关注
[经验]

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

fstat函数用来获取已经打开的文件描述符相关的文件状态信息。
1.头文件
#include
2.函数原型
int fstat(int fd, struct stat *statbuf);
3.参数
fd:文件描述符,表示已打开的文件。
statbuf:指向 struct stat 结构的指针,用于存储文件的状态信息。
4.返回值
若成功返回0,失败返回-1
5.示例:(使用fstat获取文件状态信息)
#include
#include
#include
#include
#include

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

更多回帖

发帖
×
20
完善资料,
赚取积分