为int的C / UNIX MMAP阵列 [英] C/UNIX mmap array of int
问题描述
是否有可能 MMAP
文件的完整integeres作为整数数组的?我的意思是这样的某物(不工作)
Is it possible to mmap
file full of integeres as integer array? I mean sth like this (which doesn't work)
指定的文件 tmp.in
1 2 15 1258
和类似code将该
int fd;
if ((fd = open("tmp.in", O_RDWR, 0666)) == -1) {
err(1, "open");
}
size_t size = 4 * sizeof(int);
int * map = (int *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
我希望能够调用
printf("%d\n", map[2]+1);
与预期的结果。
16
我发现使用的sscanf
解析整数字符映射,但我需要在数字阵列(也可能改变他们,让他们保存在在munmap
)。只使用POSIX函数和系统调用。
I found char mapping using sscanf
to parse integers, but I need to have numbers in array (and possibly change them and have them saved when munmap
). Using only POSIX functions and syscalls.
我发现某事在这里<一个href=\"http://stackoverflow.com/questions/17104951/mmap-reading-stale-array-of-integers-from-an-file\">mmap阅读整数数组陈旧从但我需要一个文件,文件仍然可读(所以没有二进制重新presentation)。使用 strtok的
和的atoi
迫使我用另一个数组,不是吗?最后我需要我的数据复制回到地图
。
I found sth here mmap reading stale array of integers from an file but I need file remain readable (so no binary representation). Using strtok
and atoi
forces me to use another array, doesn't it? At the end I would need to copy my data back to map
.
感谢您的帮助:)
推荐答案
没有, MMAP
给你的文件自动映射到您的地址空间中的原样的
No, mmap
gives you automatic mapping of the file into your address space as-is.
这意味着,一个文本文件将被映射为字符,而不是一个整数数组。换句话说, 1 2 15 1258
会被映射(假设ASCII编码和UNIX行尾)为:
That means that a text file will be mapped as characters rather than an array of integers. In other words, 1 2 15 1258
will be mapped (assuming ASCII encoding and UNIX line endings) as:
0x31 0x20 0x32 0x20 0x31 0x35 0x20 0x31 0x32 0x35 0x38 0x10
如果你想保持数据的文本文件中尚未有在内存中的二进制,你将不得不自己动手(双向)进行转换。
If you want to keep the data as textual in the file yet have it binary in memory, you will have to convert it yourself (both directions).
这篇关于为int的C / UNIX MMAP阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!