Linux系统调用接口

open

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

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

  • 参数解析
    1.pathname:要打开或创建的目标文件
    2.flags:打开文件时可以传入多个参数进程,用下面的一个或者多个常量进行“或”运算,构成flags.
    参数:
O_RDONLY  只读
O_WRONLY 只写
O_RDWR  读写打开
O_CREAT 文件不存在创建它
O_APPEND  追加写
  • 返回值: 成功返回新打开文件的描述符
    失败返回 -1
  • open函数具体使用哪个由具体应用场景相关,如目标文件不存在,需要open创建,则选择三个参数的open,它的第三个参数表示创建文件的默认权限,否则使用两个参数的open。

close

       #include <unistd.h>

       int close(int fd);

  • 参数fd为要关闭文件的文件描述符
  • 返回值:成功返回 0,失败返回-1

write

       #include <unistd.h>

       ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
              off_t offset);
       ssize_t write(int fildes, const void *buf, size_t nbyte);

  • 使用
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>


int main()
{
  int fd = open("myfile",O_WRONLY | O_CREAT, 0644);
  if(fd < 0)
  {
      perror("open");
      return 1;
  }
  int count = 3;
  const char* buf = "hello taotao\n";
  while(count--)
  {
     write(fd,buf,strlen(buf));
  }
  close(fd);
  return 0;
}

上述代码使用open打开并创建一个新文件并在新文件中写入3行hello taotao。

read

       #include <unistd.h>

       ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
       ssize_t read(int fildes, void *buf, size_t nbyte);

  • 使用
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>

int main()
{
  int fd = open("myfile",O_RDONLY);
  if(fd < 0)
  {
    perror("open");
    exit(1);
  }
  const char* msg = "hello taotao\n";
  char buf[1024];
  while(1)
  {
    ssize_t s = read(fd,buf,strlen(msg));
    if(s > 0)
    {
      printf("%s",buf);
    }else{
      buf[s] = 0;
      break;
    }
  }
  close(fd);
  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值