尝试open()
的文件,然后使用lseek()
或fstat()
来获取大小,但是两者的结果都是0
例如,我的行:
printf(“小尺寸:%d \ nfstat尺寸:%d \ n文件描述:%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的新手,所以将非常感谢您的帮助。
答案 0 :(得分:4)
来自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