【发布时间】:2014-12-03 11:05:04
【问题描述】:
所以我使用 mmap 然后写入另一个文件。但奇怪的是,当我的代码点击 mmap 时,它所做的是清除文件。所以我有一个填充了随机字符(AB、HAA、JAK 等)的文件。它应该做的是基本上使用 mmap 作为读取,然后将该文件写入新文件。所以第一个 if (argc == 3) 是正常的读写,第二个 if (argc ==4) 应该使用 mmap。有谁知道为什么在地球上会发生这种情况?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char const *argv[])
{
int nbyte = 512;
char buffer[nbyte];
unsigned char *f;
int bytesRead = 0;
int size;
int totalBuffer;
struct stat s;
const char * file_name = argv[1];
int fd = open (argv[1], O_RDONLY);
int i = 0;
char c;
int fileInput = open(argv[1], O_RDONLY);
int fileOutPut = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
fstat(fileInput, &s);
size = s.st_size;
printf("%d\n", size);
if (argc == 3)
{
printf("size: %d\n", size);
printf("nbyte: %d\n", nbyte);
while (size - bytesRead >= nbyte)
{
read(fileInput, buffer, nbyte);
bytesRead += nbyte;
write(fileOutPut, buffer, nbyte);
}
read(fileInput, buffer, size - bytesRead);
write(fileOutPut, buffer, size - bytesRead);
}
else if (argc == 4)
{
int i = 0;
printf("4 arg\n");
f = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fileInput, 0);
/* This is where it is being wipped */
}
close(fileInput);
close(fileOutPut);
int who = RUSAGE_SELF;
struct rusage usage;
int ret;
/* Get the status of the file and print some. Easy to do what "ls" does with fstat system call... */
int status = fstat (fd, & s);
printf("File Size: %d bytes\n",s.st_size);
printf("Number of Links: %d\n",s.st_nlink);
return 0;
}
编辑:我想提一下,第一次读写工作完美,只有当你尝试通过 mmap 进行时。
【问题讨论】:
-
argc == 4时,您没有对输出文件做任何事情。你期待会发生什么吗? -
不,我正在查看文件本身。进入之前的文件(单词)的大小约为 3,0000。之后,大小为 0。当我尝试打印 f 的第一个字符时,我意识到发生了一些奇怪的事情,但它出现了段错误。
-
您能否检查
f和MAP_FAILED,如果失败则打印errno?这应该会给你一些失败的线索。