1. 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。
stat ()函数是一个用于获取文件属性的系统调用,它返回一个包含文件元数据的结构体。在C语言中,可以使用`stat`函数来获取文件的信息,如文件大小、权限、创建时间等。stat() 函数的使用方式如下:
#include <sys/stat.h>
#include <stdio.h>
int main() {
struct stat fileStat;
if (stat("file.txt", &fileStat) == 0) {
printf("File Size: %ld bytes\n", fileStat.st_size);
printf("File Permissions: %o\n", fileStat.st_mode);
// 其他属性
} else {
perror("Error in stat");
}
return 0;
}
2. fstat()
fstat 函数原型如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int fstat(int fd, struct stat *buf);
fstat() 函数与 stat() 函数类似,不同之处在于它接受一个文件描述符作为参数,而不是文件名。使用方式如下:
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fd = open("file.txt", O_RDONLY);
if (fd != -1) {
struct stat fileStat;
if (fstat(fd, &fileStat) == 0) {
printf("File Size: %ld bytes\n", fileStat.st_size);
printf("File Permissions: %o\n", fileStat.st_mode);
// 其他属性
} else {
perror("Error in fstat");
}
close(fd);
} else {
perror("Error opening file");
}
return 0;
}
3. lstat()
lstat()与 stat、fstat 的区别在于,对于符号链接文件,stat、fstat 查阅的是符号链接文件所指向的文件对 应的文件属性信息,而 lstat 查阅的是符号链接文件本身的属性信息。
lstat 函数原型如下所示:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int lstat(const char *pathname, struct stat *buf);
函数参数列表、返回值与 stat 函数一样,使用方法也一样。