Linux---read系统函数

学习linux系统函数read.

用read读取一个文件并将内容输出到屏幕上:

 /*************************************************************************
      > File Name: MyOpen.cpp
      > Author: xuchen_allen
      > Mail: [email protected] 
      > Created Time: 2019年01月29日 星期二 10时11分33秒
************************************************************************/
  
  #include<iostream>
  using namespace std;
  #include<sys/types.h>
  #include<sys/stat.h>
  #include<fcntl.h>
  #include<unistd.h>
  
  int main()
  {
      //打开一个已经存在的文件
      int fd = open("english.txt",O_RDWR);
      if(fd == -1){
          perror("open file:");
          exit(1);
      }
  
      //读取文件内容:
      char *buf = new char[2048];
      int count = read(fd,buf,sizeof(buf));
      if(count==-1){
          perror("read fail");
          exit(1);
      }
  
      while(count){
          cout<<buf;
          count = read(fd,buf+count,sizeof(buf));//此处要将buf往后移,要不然就会死循环
     }
 
  
    //关闭文件:
     int ret = close(fd);
     cout<<"ret="<<ret<<endl;
  
 
     return 0;
     }
                            

函数

发布了158 篇原创文章 · 获赞 37 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/XUCHEN1230/article/details/86686998