gpt4 book ai didi

c - 在符合 POSIX 的 C 程序中确定二进制常规文件大小的最佳实践

转载 作者:行者123 更新时间:2023-12-01 13:54:43 25 4
gpt4 key购买 nike

我需要确定 POSIX 下二进制常规文件的文件大小(以字节为单位)。我知道如何将它与 lseek() 和 fstat() 一起使用:

#include <sys/stat.h> // for open() and fstat()
#include <fcntl.h> // for O_RDONLY
#include <unistd.h> // for lseek()

int fd = open("something.bin", O_RDONLY);
if (fd == -1)
{
perror("Unable to open file to read");
return EXIT_FAILURE;
}

// Using lseek()
const off_t size = lseek(fd, 0, SEEK_END);
if (size == (off_t) -1)
{
perror("Unable to determine input file size");
return EXIT_FAILURE;
}
// Don't forget to rewind
if (lseek(fd, 0, SEEK_SET) != 0)
{
perror("Unable to seek to beginning of input file");
return EXIT_FAILURE;
}
...

// Using fstat()
struct stat file_stat;
int rc = fstat(fd, &file_stat);
if (rc != 0 || S_ISREG(file_stat.st_mod) == 0)
{
perror("fstat failed or file is not a regular file");
return EXIT_FAILURE;
}
const off_t size = file_stat.st_size;

为什么我更喜欢一种解决方案而不是另一种?

一种方法是否比另一种方法做的更多(也许是不必要的)?

是否应该首选其他符合 POSIX 标准或标准 C 的解决方案?

最佳答案

通常 stat()、fstat() 会读取文件的元数据来为用户检索文件属性。存储文件元数据的机制可能因文件系统而异,但通常旨在提供最佳速度/时间复杂度。

“文件大小”是存储在元数据中的文件属性之一,并在各种文件操作(例如写入/追加等)中更新。此外,fstat() 不需要您“打开()”文件。

另一方面,如果文件不存在于操作系统的页面缓存中,则每个“open()”和“lseek()”操作一起都可能涉及磁盘事件,并且可能成倍增加。

因此我会推荐 fstat()。

关于c - 在符合 POSIX 的 C 程序中确定二进制常规文件大小的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com