【发布时间】:2019-08-05 11:06:04
【问题描述】:
我注意到当我使用open + lseek 查询设备的大小时,一切正常,但是当我stat 设备时,我得到的是零而不是实际的设备大小。设备很干净,没有任何文件系统,设备的第一个字节以“1234567890ABC”之类的文本开头。怎么了?
代码:
#include <sys/stat.h>
#include <dirent.h>
bool
GetFileSize(const char* pPath, uint64_t& Size)
{
pPath = "/home/sw/.bashrc";
pPath = "/dev/sda";
struct stat buffer;
if (stat(pPath, &buffer))
{
printf("Failed to stat file. Error: %s. FilePath: %s\n", strerror(errno), pPath);
return false;
}
printf("File size by stat: %" PRIu64 " WTF?\n", buffer.st_size);
//
// Note: It's strange, but stat::st_size from the stat call is zero for devices
//
int File = open(pPath, O_RDONLY);
if (File < 0)
{
printf("Failed to open file. Error: %s. FilePath: %s\n", strerror(errno), pPath);
return false;
}
long off = lseek(File, 0, SEEK_END);
if (off == (off_t)-1)
{
printf("Failed to get file size. Error: %s. FilePath: %s\n", strerror(errno), pPath);
close(File);
return false;
}
close(File);
printf("File size by lseek: %" PRIu64 "\n", off);
fflush(stdout);
Size = off;
return true;
}
输出:
File size by stat: 0 Huh?
File size by lseek: 34359738368
如果我将 stat 用于常规文件,则一切正常(用“/dev/sda”注释掉该行):
File size by stat: 4019 Huh?
File size by lseek: 4019
【问题讨论】:
-
欢迎来到“统计信息不同于寻求+告诉信息”。
-
我不相信使用
PRIu64打印尺寸,除非您将尺寸转换为uint64_t。也就是说,如果出现问题,您可能不会得到零。