我正在尝试使用 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/