【问题标题】:mmap is wiping my file instead of copying itmmap 正在擦除我的文件而不是复制它
【发布时间】: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 的第一个字符时,我意识到发生了一些奇怪的事情,但它出现了段错误。
  • 您能否检查fMAP_FAILED,如果失败则打印errno?这应该会给你一些失败的线索。

标签: c mmap


【解决方案1】:

如果您的意思是它正在清除您的 destination 文件,那么是的,这正是您的代码要做的事情。

它使用截断打开目标,然后在您的 argc==4 部分中,您映射输入文件,但绝对不做任何事情来将数据传输到输出文件。

您需要一个带有某种描述的while 循环,类似于argc==3 情况下的循环,但它将映射内存 中的字节写入fileOutput 描述符。

【讨论】:

  • 不,它正在清除源文件。 ./mycp words words2
  • @Jen,您的代码中有很多不检查返回值的地方。在mmap 之后f 的值是多少。确保它不是 MAP_FAILED。
  • 失败了,就是问题所在。我不知道为什么会这样。
  • @Jen,可能是因为您提供的大小为零,假设文件已被截断。
猜你喜欢
  • 2013-08-09
  • 1970-01-01
  • 2011-04-16
  • 2023-04-04
  • 2023-03-22
  • 1970-01-01
  • 2013-09-23
相关资源
最近更新 更多