Linux——基础IO

前言:大佬写博客给别人看,菜鸟写博客给自己看。我是菜鸟

认知1:

stdin   → 标准输入 → 键盘文件

stdout → 标准输出 → 显示器文件

stderr  → 标准错误 → 显示器文件

:把显示器以及键盘看作是文件,广义的说:Linux下一切都是文件

1.系统接口的使用(open/close/write/read)

写一段简单的代码来实现一下:

  #include <stdio.h>                                                                                                                                                              
  #include <sys/types.h>
  #include <sys/stat.h>
  #include <sys/fcntl.h>
  #include <string.h>
  #include <stdlib.h>
  #include <unistd.h>
  int main()
  {
      int fd = open("log.txt",O_CREAT | O_WRONLY | O_TRUNC,0666);
      if(fd < 0)
      {
          perror("open");
          exit(1);
      }
      const char* msg = "hello kivotos\n";
      write(fd,msg,strlen(msg));
  
      close(fd);
      return 0;
  }
  #include <stdio.h>
  #include <sys/types.h>
  #include <sys/stat.h>
  #include <sys/fcntl.h>
  #include <string.h>
  #include <stdlib.h>
  #include <unistd.h>
  int main()
  {
      int fd = open("log.txt",O_RDONLY);
      if(fd < 0)
      {
         perror("open");
         exit(1);
      }
      // const char* msg = "hello kivotos\n";
      // write(fd,msg,strlen(msg));
      
      char buffer[64];
      int n = read(fd,buffer,sizeof(buffer)-1);
      if(n>0)                                                                                                                                                                     
      {
          buffer[n] = 0;
          printf("%s",buffer);
      }
      close(fd);
     
      return 0;
  }

int open(const char *pathname, int flags, mode_t mode);

pathname:任意路径

flag:常用的有以下几个

O_RDONLY  → 只读

O_WRONLY → 只写

O_RDWR     → 读写

O_CREAT    → 文件不存在则创造(若路径下文件不存在,则一定要加)

O_TRUNC   → 将文件中的内容删除并重写

O_APPEND → 在文件新的一行追加

mode:当创建文件时࿰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值