我正在尝试运行此代码,而我以 - 结尾 值:1 值:0.000000
我的问题是为什么两个结果不同?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
int main ()
{
int fd;
struct stat mystat;
void *pmap;
int i,integer;
double *values;
int32_t *mapped_baseA;
int32_t fdA;
fd = open("test.txt",O_RDWR); // a text file containing- 1 2 3 4 5
if(fd==-1)
{
perror("open");
exit(1);
}
if(fstat(fd,&mystat)<0)
{
perror("fstat");
close(fd);
exit(1);
}
pmap = mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
if(pmap==MAP_FAILED)
{
perror("mmap failed");
close(fd);
exit(1);
}
//strncpy(pmap,"That is my name",15);
sscanf (pmap, " %d", &integer);
printf("value: %d \n", integer);
//打印从字符串扫描后的值。
values = (double *) mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
printf("value: %lf \n", values[1]);
//打印指针的值 munmap(pmap,mystat.st_size);
close(fd);
return 0;
}
最佳答案
仔细阅读(多次)mmap(2) 。注意:
A file is mapped in multiples of the page size.
以及ERRORS
部分
EINVAL
We don't like addr, length, or offset (e.g., they are too large, or not aligned on a page boundary).
也可以考虑使用strace(1)在您的可执行文件上。
当然,内存映射只是将映射文件的 View (作为字节的原始序列)提供给 process通过修改其 virtual address space 。它显然不会进行任何转换(您可以在该 View 的某些部分使用 sscanf(3) 或 strtol(3) 来进行从数字的 UTF8 或 ASCII 字符串表示形式到其机器表示形式的转换)。
关于c - 这段用 mmap 读取的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162637/