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

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
面向函数的unix环境编程练习要素

面向函数的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)

441113422 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档