c - 尝试将 2GB 写入文件,看到写入的数量不正确

标签 c file-io posix

我正在尝试使用 pwrite 将 2GB 写入文件,但我下面的代码写入的数量较少。
但是,如果我使用 2 个 1GB 的 pwrite 调用总共写入 2GB,那就行了。

预期文件大小:2147483648 字节 (2GB),观察到:2147479552

编译为:gcc -Wall test.c -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE=1 -D_XOPEN_SOURCE=600
64 位 Opensuse 上的 gcc v 4.5.0

这是完整的程序。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    size_t size = 2147483648; //2GB
    off_t offset = 0;
    int fd;

    char *buf = (char*) malloc (size * sizeof(char));
    if(buf == NULL)
    {
        printf("malloc error \n");
        exit(-1);
    }

    if(-1 == (fd = open("/tmp/test.out", O_RDWR|O_CREAT, 0644)))
    {
        fprintf(stderr, "Error opening file. Exiting..\n");
        free(buf);
        exit(-1);
    }

    if(-1 == (pwrite(fd, buf, size, offset)))
    {
        perror("pwrite error");
        free(buf);
        exit(-1);
    }

    free(buf);
    return 0;
}

最佳答案

从 pwrite 手册页:

Description

pwrite() writes up to count bytes from the buffer starting at buf to the file descriptor fd at offset offset. The file offset is not changed.

Return Value

On success, the number of bytes written is returned (zero indicates that nothing was written), or -1 on error, in which case errno is set to indicate the error.



请注意, pwrite() 不需要写入您要求的字节数。它可以少写,这不是错误。通常,您会在循环中调用 pwrite() - 如果它没有写入所有数据,或者它因 errno==EINTR 而失败,那么您将再次调用它来写入其余数据。

关于c - 尝试将 2GB 写入文件,看到写入的数量不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9400623/

相关文章:

c++ - IO 文件代码不一致

C#2.0逐行读取并复制Xml文件?

c - 为什么有些函数既返回返回值又返回写入指针传递的结果?

c - 这个字符序列 "\033[H\033[J"在 C 中做了什么?

c - GCC 以相反的顺序编译 EEPROM 地址

c - 使用指针执行 strcat 时出现段错误(核心已转储)

c - 读取纺织品并添加到 C 中的链接列表

c - 在正则表达式中匹配正斜杠

c - 如何使用正则表达式捕获组?

c++ - C 等价于 C++ STL