Linux 下可以使用 stat 命令查看文件的属性,其实这个命令内部就是通过调用 stat()函数来获取文件属性的,stat 函数是 Linux 中的系统调用,用于获取文件相关的信息。(可通过"man 2 stat"命令查看):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *buf);
pathname:用于指定一个需要查看属性的文件路径。
buf:struct stat 类型指针,用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct stat 变量的指针,获取到的文件属性信息就记录在 struct stat 结构体中。
返回值:成功返回 0;失败返回-1,并设置 error。
示例代码:
获取文件的 inode 节点编号以及文件大小,并将它们打印出来。
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct stat file_stat;
int ret;
/* 获取文件属性 */
ret = stat("./test_file", &file_stat);
if (-1 == ret)
{
perror("stat error");
exit(-1);
}
/* 打印文件大小和 inode 编号 */
printf("file size: %ld bytes\n"
"inode number: %ld\n",
file_stat.st_size,
file_stat.st_ino);
exit(0);
}
测试验证:

从图中可以得知,此文件的大小为 4060 个字节,inode 编号为 656929
接下来编译测试程序,并运行

本文介绍了在Linux环境下如何使用stat命令和stat系统调用来获取文件的属性,如文件大小和inode编号。示例代码展示了如何通过编程方式获取这些信息,并提供了编译和运行测试的说明。

2338

被折叠的 条评论
为什么被折叠?



