c - 这段用 mmap 读取的代码有什么问题?

标签 c mmap

我正在尝试运行此代码,而我以 - 结尾 值: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/

相关文章:

c - linux - mmap 共享最大大小

c++ - 将 flann 与内存映射索引一起使用

c - 为什么我不能写入文件 mmaped

c - 如何为指向指针的指针分配内存?

c - 使用 malloc/free 时的 __lll_lock_wait_private ()

c++ - 在单元测试项目中包含 .c 文件并从多个 cpp 文件访问它,而不会出现链接问题

c - dup2 重定向 printf 失败?

c - 使用位操作减少缓存开销

c++ - 从 mmap() 读取时 ntohl() 返回 0

c - 运行时检查失败 #0 : Why am I getting this and what does it mean?