问题描述
我想使用mmap从文件读取整数的矩阵。如果我收到它作为char指针从mmap函数,我看到一切正确,但如果我使用int指针,它给我陈旧的数据。 使用char指针的问题是,我需要使用strtok或其他方法解析整个字符串,并逐个获取整数。我的矩阵大小将是4k * 4k,因此使得许多调用sscanf和strtok不高效。请查看程序和输出
#define INTS 3 * 3
int main b $ b {
FILE * in = fopen(int_file,rb);
int * ints =(int *)mmap(0,INTS * sizeof(int),
PROT_READ,MAP_FILE | MAP_PRIVATE,fileno(in),0);
fclose(in);
for(int i = 0; i std :: cout< ints [i]< std :: endl;
}
munmap(ints,INTS * sizeof(int));
return 0;
}
int_file的内容为
510 20 30
40 50 60
100 200 10000
/ p>
540029237
857747506
808716848
540030240
822751286
84097028
正在打印文本的ACSII值。
您的文字如下:
510 20 30 ...
从ASCII表(以解释我想说明的):
否。 ASCII(十六进制)
空格 - > 20
0 - > 30
1 - > 31
2 - > 32
3 - > 33
5 - > 35
int
> 4 字节大小,因此,首先4
字节:
ASCII,
510
在内存中给出35 31 30 20
,0x20303135
(540029237
为十进制)。
类似地,下4
字节20 3
给出0x33203032
(857747506
为十进制)。
这是你得到的。
在这种情况下,你需要使用atoi()或类似的方法将每个ACSII转换为整数。
但你可以将整数存储为二进制值本身,而不是保持为ASCII。该文件将不是人类可读的,但它会做你的目的。
I'm trying to read matrix of integers from file using mmap. If I receive it as char pointer from mmap function, I see everything correct but if I use int pointer, it gives me stale data. Problem with using char pointer is that I need to parse whole string using strtok or something else and get integers one by one. My matrix size is going to be 4k * 4k hence making that many calls to sscanf and strtok is not efficient. Please look at the program and output
#define INTS 3 * 3 int main() { FILE* in = fopen("int_file", "rb"); int* ints = (int*)mmap(0, INTS * sizeof(int), PROT_READ, MAP_FILE | MAP_PRIVATE, fileno(in),0); fclose(in); for(int i = 0; i < INTS; ++i) { std::cout << ints[i] << std::endl; } munmap(ints, INTS * sizeof(int)); return 0; }
Contents of int_file is
510 20 3040 50 60100 200 10000
Output
54002923785774750680871684854003024082275128684097028
解决方案The ACSII value of the text is getting printed.
Your text seems like:
510 20 30...
From ASCII table (to explain what I want to tell):
No. ASCII (hex) Space -> 20 0 -> 30 1 -> 31 2 -> 32 3 -> 33 5 -> 35
int
is4
byte in size, so, taking first4
bytes:Converting to ASCII,
"510 "
gives"35 31 30 20"
in memory which is0x20303135
(540029237
as decimal) for a little endian machine.Similarly, next4
bytes"20 3"
gives0x33203032
(857747506
as decimal).This is what you are getting.You need to convert each ACSII to integer using atoi() or similar, in this case.
But you may store your integers as their binary value itself rather than keeping it as ASCII. The file will not be human readable but it will do your purpose.
这篇关于mmap从文件读取整数的陈旧数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!