当前位置:首页 > 操作系统 > Linux

linux c++(IO & 第一篇)

文件IO

        #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

    
  • open
    • int open(const char *pathname, int flags);
    • int open(const char *pathname, int flags, mode_t mode);
    • fd:文件描述符 O_RDWR:模式 0666:若要创建文件就是文件创建的权限mode&~umask
    • int fd = open(argv[1],O_RDWR|O_CREAT,0666);
        #include <unistd.h>

    
  • close
    • fd是文件描述符
    • int close(int fd);
        #include <unistd.h>

    
  • read
    • 返回值为读取内容的大小 fd:文件描述符 buf:缓冲区 count:缓冲区大小
    • ssize_t read(int fd, void *buf, size_t count);
        #include <unistd.h>

    
  • write
    • buf:内容 count:写入内容的大小
    • ssize_t write(int fd, const void *buf, size_t count);

总体示例

          #include <stdio.h>
  #include <sys/types.h>    
  #include <sys/stat.h>
  #include <fcntl.h>
  #include <unistd.h>
  #include <string.h>
  
  int main(int argc,char *argv[])
  {
      if(argc !=2)
      {   
          printf("err: ./app filenamen");
          return 0;
      }   
      int fd = open(argv[1],O_RDWR|O_CREAT,0666);
      char *str="xiaozhao";
      write(fd,str,strlen(str));
      //文件读写位置此时到末尾了
      lseek(fd,0,SEEK_SET);//移动文件指针到开头
      char buf[8]={0};
      int ret;
      do{ 
          ret = read(fd,buf,sizeof(buf));
          write(STDOUT_FILENO,buf,ret);
      }while(ret!=0);
      close(fd);
      
  }   

    

原文:https://www.cnblogs.com/lodger47/p/14727218.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐