日期:2014-05-16  浏览次数:20675 次

程序很简单,结果很纠结啊,都进来看看吧
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>

int main(int argc, char **argv)
{
    int fd,i;
    int flength;
    char *p;
    char tmp;
    
    if (argc<2) {
        printf("please enter a filename\n");
exit(-1);
    }
    
    fd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
    if (fd<0) {
        perror("open");
exit(-1);
    }

    flength=lseek(fd,20,SEEK_SET);
    write(fd, " ", 1);
    printf("flength=%d\n", flength);
    if (flength<0) {
        perror("lseek error");
exit(-1);
    }

    p=(char *)mmap(NULL,flength,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if (p==MAP_FAILED) {
        perror("mmap error");
exit(-1);
    }

    tmp='a';
    for (i=0; i<flength-1; i++) {
p[i]=tmp;
tmp+=1;
    }

    p[i]='\0';

    printf("initialize over.......p=%s\n", p);
    
    sleep(10);

    munmap(p,flength);
    
    printf("unmap ok\n");
    return 0;
}


我认为的理想输出结果应该是19个字符a-s,然后赋一个\0,就ok了啊,为什么用gedit打开会错呢,而且用vim打开在‘s’后面还跟了个什么乱码???真心不懂啊,求解释!!!!
vim打开文件如下截图:
linux 文件io mmap

------解决方案--------------------
因为你写了20个字符总共,加了那个空格,一开始的,
但是你的文件长度设置的是21,所以有一个位置什么都没写
就是0,所以就这样了。你可以
    for (i=0; i<flength-1; i++) {
的-1去掉
------解决方案--------------------
你开始的时候已经写了一个字符了:write(fd, " ", 1);,所以总共21个;
末尾那个^@估计就是'\0',48行改成p[i]=' ';应该就行了;
最后记得close(fd);,关闭文件描述符;

------解决方案--------------------
文件里面为什么要写\0???\0是在内存中标记字符串结束的。。