我正在尝试为文件操作预分配磁盘空间,但是,我遇到了一个奇怪的问题,即当我调用 posix_fallocate 为以附加模式打开的文件分配磁盘空间时,它只分配一个字节,并且文件内容也是意外的。有人知道这个问题吗?我的测试代码是,
#include <cstdio>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cerrno>
int main(int argc, char **argv)
{
FILE *fp = fopen("append.txt", "w");
for (int i = 0; i < 5; ++i)
fprintf(fp, "## Test loop %d\n", i);
fclose(fp);
sleep(1);
int fid = open("append.txt", O_WRONLY | O_APPEND);
struct stat status;
fstat(fid, &status);
printf("INFO: sizeof 'append.txt' is %ld Bytes.\n", status.st_size);
int ret = posix_fallocate(fid, (off_t)status.st_size, 1024);
if (ret) {
switch (ret) {
case EBADF:
fprintf(stderr, "ERROR: %d is not a valid file descriptor, or is not opened for writing.\n", fid);
break;
case EFBIG:
fprintf(stderr, "ERROR: exceed the maximum file size.\n");
break;
case ENOSPC:
fprintf(stderr, "ERROR: There is not enough space left on the device\n");
break;
default:
break;
}
}
fstat(fid, &status);
printf("INFO: sizeof 'append.txt' is %ld Bytes.\n", status.st_size);
char *hello = "hello world\n";
write(fid, hello, 12);
close(fid);
return 0;
}
预期的结果应该是,
## Test loop 0
## Test loop 1
## Test loop 2
## Test loop 3
## Test loop 4
hello world
但是,上述程序的结果是,
## Test loop 0
## Test loop 1
## Test loop 2
## Test loop 3
## Test loop 4
^@hello world
那么,什么是“^@”?
消息显示,
INFO: sizeof 'append.txt' is 75 Bytes.
INFO: sizeof 'append.txt' is 76 Bytes.
有什么线索吗?
谢谢