`fstat` 函数用于获取已打开文件的状态信息。它需要两个参数:
文件描述符 (fd):
这是一个整数,代表已经打开的文件的标识符。
指向 `stat` 结构体的指针 (buf):
这是一个指向 `stat` 结构体的指针,用于存储文件的状态信息。
`fstat` 函数成功时返回 0,失败时返回 -1。如果发生错误,错误代码会保存在 `errno` 中。
下面是一个使用 `fstat` 函数的示例代码:
```c
include include include include int main() { int fd; struct stat buf; // 打开文件 fd = open("example.txt", O_RDONLY); if (fd == -1) { perror("open"); return 1; } // 获取文件状态 if (fstat(fd, &buf) == 0) { printf("文件大小: %ld\n", (long)buf.st_size); printf("文件权限: %s\n", (buf.st_mode & S_IRUSR) ? "读" : "-"); printf("文件权限: %s\n", (buf.st_mode & S_IWUSR) ? "写" : "-"); printf("文件权限: %s\n", (buf.st_mode & S_IXUSR) ? "执行" : "-"); printf("文件所有者UID: %ld\n", (long)buf.st_uid); printf("文件所有者GID: %ld\n", (long)buf.st_gid); printf("最后访问时间: %ld\n", (long)buf.st_atime); printf("最后修改时间: %ld\n", (long)buf.st_mtime); printf("最后状态修改时间: %ld\n", (long)buf.st_ctime); } else { perror("fstat"); close(fd); return 1; } // 关闭文件 close(fd); return 0; } ``` 在这个示例中,我们首先使用 `open` 函数打开一个名为 `example.txt` 的文件,并检查是否成功。然后,我们调用 `fstat` 函数来获取文件的状态信息,并打印出来。最后,我们关闭文件描述符。 请注意,这个示例是基于 C 语言的,如果你使用的是其他编程语言,语法可能会有所不同。例如,在 Python 中,你可以使用 `os.fstat()` 方法来获取已打开文件的状态信息,如下所示: ```python import os 打开文件 fd = os.open("foo.txt", os.O_RDWR | os.O_CREAT) 获取文件状态信息 info = os.fstat(fd) 打印文件状态信息 print("文件信息 :", info) print("文件 UID :", info.st_uid) print("文件 GID :", info.st_gid) ``` 在这个 Python 示例中,我们使用 `os.open` 函数打开一个文件,并获取文件描述符 `fd`。然后,我们调用 `os.fstat` 方法,并将文件描述符作为参数传递,以获取文件的状态信息。最后,我们打印出文件的状态信息。