基本概念
struct stat 是 C 语言中用于获取文件状态信息的结构体。它在 <sys/stat.h> 头文件中定义,主要通过 stat(), fstat(), 和 lstat() 等函数来填充其字段。以下是 struct stat 的详细信息:
- 
定义: cstruct stat { dev_t st_dev; /* 包含文件的设备的 ID */ ino_t st_ino; /* Inode 编号 */ mode_t st_mode; /* 文件类型和模式 */ nlink_t st_nlink; /* 硬链接数 */ uid_t st_uid; /* 文件所有者的用户 ID */ gid_t st_gid; /* 文件所有者的组 ID */ dev_t st_rdev; /* 设备 ID(如果是特殊文件) */ off_t st_size; /* 总大小,以字节为单位 */ blksize_t st_blksize; /* 文件系统 I/O 的块大小 */ blkcnt_t st_blocks; /* 分配给文件的 512B 块的数量 */ struct timespec st_atim; /* 最后访问时间 */ struct timespec st_mtim; /* 最后修改时间 */ struct timespec st_ctim; /* 最后状态更改时间 */ #define st_atime st_atim.tv_sec /* 向后兼容性 */ #define st_mtime st_mtim.tv_sec #define st_ctime st_ctim.tv_sec };这个结构体包含了文件的基本信息,例如大小、所有者、权限、最后访问和修改时间等。 
- 
函数: - int stat(const char *restrict pathname, struct stat *restrict statbuf);通过文件的路径名获取文件状态信息,填充- struct stat结构体。
- int fstat(int fd, struct stat *statbuf);通过文件描述符获取文件状态信息,填充- struct stat结构体。
- int lstat(const char *restrict pathname, struct stat *restrict statbuf);类似- stat(),但如果路径名是一个符号链接,- lstat()返回链接本身的信息,而不是链接指向的文件的信息。
 
- 
使用 : 通过调用 stat(),fstat(), 或lstat()函数并传递struct stat结构体的地址作为参数,可以获取文件的状态信息。这些函数会填充struct stat结构体的字段,以便我们可以检索所需的文件信息。例如,可以使用struct stat结构体的st_size字段来获取文件的大小,或使用st_mode字段来获取文件的权限和类型。
struct stat 是一个非常重要和常用的结构体,它允许我们在 C 程序中处理文件和文件系统相关的任务。在编写涉及文件操作的 C 程序时,通常会使用到 struct stat 结构体以及相关的系统调用。
示例
下面,我们来演示如何使用 struct stat 结构体和 stat() 函数来检索特定文件的一些基本信息。假设我们想要获取一个名为 "example.txt" 的文件的大小、所有者 ID 和最后修改时间。
            
            
              c
              
              
            
          
          #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
    struct stat statbuf;
    // 获取 "example.txt" 文件的状态信息
    if (stat("example.txt", &statbuf) == -1) {
        perror("stat");
        return 1;
    }
    // 打印文件的大小
    printf("File size: %lld bytes\n", (long long) statbuf.st_size);
    // 打印文件所有者的用户 ID
    printf("Owner UID: %d\n", statbuf.st_uid);
    // 打印文件的最后修改时间
    printf("Last modification time: %ld\n", (long) statbuf.st_mtime);
    return 0;
}在上述代码中,首先包含了必要的头文件,然后在 main() 函数中声明了一个 struct stat 类型的变量 statbuf。接着,调用 stat() 函数,传递文件名 "example.txt" 和 statbuf 的地址作为参数。如果 stat() 函数成功执行,它将填充 statbuf 结构体的字段,我们就可以通过 statbuf 结构体来访问文件的状态信息,例如文件大小 (st_size)、文件所有者的用户 ID (st_uid) 和文件的最后修改时间 (st_mtime)。
在实际编程中,通过 struct stat 结构体和相关的系统调用,我们可以方便地获取和处理文件及文件系统相关的信息,从而实现更为复杂的文件操作和管理任务。