面向函数的unix环境编程练习.doc

面向函数的unix环境编程练习 函数练习 1.对mmap映射地址操作 mmap(), fstat() mmap(): 将文件和设备空间映射到内存中,内存操作比磁盘更快。映射成功返回内存地址,是被返回-1.之后可以直接对映射的地址进行操作。 fstat()获取文件的状态。 #include stdio.h #include unistd.h #include sys/mman.h #include sys/types.h #include sys/stat.h #include fcntl.h #include stdlib.h #include errno.h int main(){ int fd=open(doc1,O_RDONLY|O_CREAT,0755); if(fd == -1){ perror(open ); exit(1); } struct stat info; fstat(fd,info); /* start set NULL, means system set it. */ /* PROT_READ means memory can be read. */ /* MAP_PRIVATE means create a copy file, not influce origin file. */ void *start=mmap(NULL,info.st_size,PROT_READ,MAP_PRIVATE,fd,0); if(start == MAP_FAILED) { perror(mmap ); exit(1); } printf(%s,(char *)start); munmap(start,info.st_size); close(fd); return 0; } 本程序将打印文件的内容。如果文件的内容为空,那么将会出现,invalid argument的错误。 2.从标准输入到标准输出 read(), write() #include stdio.h #include sys/types.h #include sys/stat.h #include fcntl.h #include unistd.h int main(){ int n; char buf[1000]; while((n=read(STDIN_FILENO,buf,1000))0){ //printf(output: ); if(write(STDOUT_FILENO,buf,n)!=n){ printf(write error\n); } } if(n0) printf(read error\n); return 0; } /* $ ./stdin_out I sf I sf sd sd sdfsdf sdfsdf //output: output: output: */ read()函数是你输入什么,它读取什么的严格类函数。(除了ctrl+D,ctrl+C等特殊情况) 3.查看标准输入的读写属性 fcntl() 使用fcnt()查看文件的属性。 #include unistd.h #include stdio.h #include fcntl.h int main(){ int flag=fcntl(STDIN_FILENO,F_GETFL,0); if(flag0) { perror(error: ); return -1; } int result=flag O_ACCMODE; if(result == O_RDONLY){ printf(stdin read only\n); } else if(result == O_WRONLY){ puts(stdin write only); } else if(result == O_RDWR){ puts(stdin read and write); } else puts(stdin unknown mode); if(flag O_APPEND) puts(stdin append); if(flag O_NONB

文档评论(0)

1亿VIP精品文档

相关文档