我以为我已经弄清楚了,但我遇到了总线错误。它所要做的就是获取一些文本文件,使用 mmap,然后在没有临时文件的情况下反转内容。我所做的就是映射它,然后删除该文件并从 mmap 指针的末尾开始将其从内存中写入。当我使用 cout 执行此操作时,这是有效的,但由于某种原因,对文件执行此操作时出现错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/io.h>
#include <sys/mman.h>
main(int argc, char *argv[])
{
unsigned char *f, *g;
int size;
struct stat s;
const char * file_name = argv[1];
int fd = open(argv[1], O_RDONLY);
int status = fstat(fd, &s);
size = s.st_size;
int i;
f = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fd, 0);
//g = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fd, 0);
for(i = 0; i < size; i++) {
char c;
c = f[i];
putchar(c);
}
//ABOVE THIS WORKS
// int z = 0;
//while(f[z] != NULL) {
//z++;
// printf("%d", z);
// }
int x;
int y = 0;
close(fd);
FILE *f1;
f1 = fopen(argv[1], "w+");
for(x = size - 1; x >= 0; x--)
{
char c;
c = f[x];
fputc(c, f1);
}
}
最佳答案
因为您使用 w
打开文件,所以将文件截断为 0 长度。 mmap 手册页说:
The effect of changing the size of the underlying file of a mapping on the pages that correspond to added or removed regions of the file is unspecified.
无论如何,在我看来,你也应该使用 PROT_WRITE
调用 mmap
,这样你就可以反转内存中的数组 f
。然后您不必再次打开该文件。确保使用 MMAP_SHARED,并在完成共享内存修改后调用 munmap()。您需要 MMAP_SHARED,因为使用 MMAP_PRIVATE:
Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file.
您应该调用 munmap() 因为:
The file may not actually be updated until msync(2) or munmap() is called.
如果您退出程序而不调用munmap(),内存将自动为您取消映射。但自己关闭/释放/取消映射事物而不是直接退出是一个好习惯。
(编辑:感谢 Adam Rosenfield 和 EOF 对我原来答案的更正。)
关于c - 使用 mmap 就地反转文本文件——出现总线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878472/