假设输入文件是文本文件(不是可以有整数或任何二进制数据写入其中的二进制文件),您的文件将被映射为长度等于文件大小的字符串。
一旦这个字符串被映射到内存中,您就可以使用指针访问各个字符。
我希望能够调用 printf("%d\n", map[2]+1);
地图[2]+1
这将只是增加字符的 ASCII 值。
据我了解,您希望将文件映射到内存并更改整数等值。
只要文件是文本文件,这是不可能的。
我的建议是将文件映射到内存中,读取字符,进行解析(在您的情况下查找空格)并更改字符值。
这里有一个示例代码:
[root@mohitsingh memoryMap]# cat sample.txt
12345
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#define FILEPATH "./sample.txt"
#define NUMINTS (5)
#define FILESIZE (NUMINTS * sizeof(int))
int main(int argc, char *argv[])
{
int i;
int fd;
char *map; /* mmapped array of char */
fd = open(FILEPATH, O_RDWR);
if (fd == -1) {
perror("Error opening file for reading");
exit(EXIT_FAILURE);
}
map = mmap(0, FILESIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
/* Read the file char-by-char from the mmap
**/
for (i = 0; i <NUMINTS; ++i) {
printf("%d: %c\n", i, map[i]);
}
/*change the character value
*Implement your own logic here to change the values as integer
*/
map[2]='9';
if (munmap(map, FILESIZE) == -1) {
perror("Error un-mmapping the file");
}
close(fd);
return 0;
}
[root@mohitsingh memoryMap]# gcc test.c
[root@mohitsingh memoryMap]# ./a.out
0:1
1:2
2:3
3:4
4:5
[root@mohitsingh memoryMap]# cat sample.txt
12945