我尝试了一个简单的 mmap
相关的 C 代码片段:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int fd;
char* mapped_mem;
int flength = 1024;
void* start_addr = 0;
if (argc < 2) {
printf("usage: %s filename\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
flength = lseek(fd, 1, SEEK_END);
write(fd, "\0", 1);
lseek(fd, 0, SEEK_SET);
printf("fd=%d, flength=%d\n", fd, flength);
mapped_mem = mmap(start_addr, flength, PROT_READ, MAP_PRIVATE, fd, 0);
printf("%s\n", mapped_mem);
close(fd);
munmap(mapped_mem, flength);
return 0;
}
但是我发现每次我在数据文件上执行它时,^@^@
都会附加到这个文件上。那么这是怎么回事?
最佳答案
您的程序首先将文件末尾移动 1 个字节(使用 lseek
),然后在那里写入一个零字节(使用 write
)。实际上,两个零字节附加到您的文件,其中一个字节填充文件末尾和写入位置之间的空白。
mmap
在这方面没有任何改变。损害已经造成。
关于c - 为什么在使用 mmap 时会附加额外的字符 ^@?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519638/