我被要求使用 usjng lseek 命令(不使用 stat)查找文件的大小,我编写了以下代码
int main()
{
字符 buf[100], fn[10];
int fd,我;
printf("请输入文件名\n");
scanf("%s", fn);
fd = open(fn, O_RDONLY);
int size = lseek(fd, 0, SEEK_END);
printf("大小为 %d", size);
关闭(fd);
}
但是我得到的文件大小是-1,我哪里出错了
最佳答案
来自 lseek
文档可用 online :
RETURN VALUE
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.
所以你必须检查 errno
(如果 lseek
返回 -1
则打印它):
来自同一 link 的可能错误列表:
ERRORS
EBADF fd is not an open file descriptor. EINVAL whence is not valid. Or: the resulting file offset would be negative, or beyond the end of a seekable device. ENXIO whence is SEEK_DATA or SEEK_HOLE, and the file offset is beyond the end of the file. EOVERFLOW The resulting file offset cannot be represented in an off_t. ESPIPE fd is associated with a pipe, socket, or FIFO.
在您的情况下,很可能是 EBADF。
关于c - 在c中使用lseek命令获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52050495/