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);

lseek的作用

No.1 移动文件读写位置
No.2 计算文件大小
int num =  lseek(fd,0,SEEK_END);
printf("num = %d\n",num);
No.3 拓展文件 && truncate也可以实现扩展文件
int fd =open(argv[1],O_WRONLY|O_CREAT,0666);
//扩展文件
int ret = lseek(fd,1024,SEEK_END);
//需要至少写一次,否则不能保存
write(fd,"a",1);

总体示例

  #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 filename\n");
          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);
      
  }   

posted on 2021-05-03 11:53  lodger47  阅读(283)  评论(0)    收藏  举报

导航