无法使用文件描述符通过 fstat() 或 lseek() 获取文件大小

标签 c linux bash file file-io

尝试open()文件,然后使用 lseek() 获取大小或fstat()但两者的结果都是 0 的大小

例如我的行:

printf("lseek size : %d\nfstat size : %d\nfile desc: %d\n", fileSize, mystat.st_size, fd);

使用包含内容的文件data1:

Jacobs-MBP:Desktop Kubie$ cat data1
2.3
3.1
5.3
1.1

打印:

Jacobs-MBP:Desktop Kubie$ ./a.out 4 data1
byte size: 4
Opened: data1
lseek size : 0
fstat size : 0
file desc: 3

下面是我的程序,目的是mmap()文件存入内存以用于其他目的。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <time.h>

int main(int argc, char * argv[]) {

        int fd;
        struct stat mystat;
        void * pmap;
        int fileSize;

        if (argc < 3) { printf("wrong # args\n"); return 0; }
        if (argc > 3) { printf("wrong # args\n"); return 0; }

        sscanf(argv[1], "%d", &byteSize);

        printf("byte size: %d\n", byteSize);

        fd = open(argv[2], O_RDWR | O_TRUNC);
        if (fd == -1) {
                perror("Error opening file!");
                exit(EXIT_FAILURE);
        } else {
                printf("Opened: %s\n", argv[2]);
        }

        if (fstat(fd, &mystat) < 0)  {
                perror("fstat error!");
                close(fd);
                exit(1);
        }

        lseek(fd, 0, SEEK_END);
        fileSize = lseek(fd, 0, SEEK_CUR);

        printf("lseek size : %d\nfstat size : %d\nfile desc: %d\n", fileSize, mystat.st_size, fd);

        pmap = mmap(0, fileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (pmap == MAP_FAILED) {
                perror("mmap error!");
                close(fd);
                exit(1);
        }

        return 0;

}

我还注意到 data1 的内容该程序完成后文件将被删除。

确实是 C 新手,因此我们将非常感谢任何帮助。

最佳答案

来自open

   O_TRUNC
          If  the  file  already  exists  and  is a regular file and the open mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to
          length 0.  If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored.  Otherwise the effect of O_TRUNC is unspecified.

你的代码确实

fd = open(argv[2], O_RDWR | O_TRUNC);

按照上面的描述

如果文件已经存在并且是常规文件并且打开​​模式允许写入(即 O_RDWR 或 O_WRONLY),它将被截断为长度 0

关于无法使用文件描述符通过 fstat() 或 lseek() 获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52921963/

相关文章:

.net - 循环浏览 IE 8 中的所有选项卡

linux - 管道输出切割

html - 下载 HTML 页面 + 所有组件的最佳工具/库

c++ - 在 C++ 中执行 shell 命令时强制环境 bash

bash - $(...) 和 `...` 有什么区别

c - 用C语言演示虚拟内存

C 程序 - 在编译器中标记为未声明的结构

c - 为什么这个循环只执行了 4 次?

c++ - 在 WinCE 和 Linux 上获取/设置 SystemTimeAdjustment

bash - 从字符串中提取版本号