Open_Read_Write函数基本使用

先来一个小插曲,我们知道read函数等是系统调用函数,应该在第二页的手册里头,可是我man 2 read的时候却找不到,由此到/usr/sharead/man/man2目录下查看的时候发现此目录为空,所以我就重新安装一下man手册。:

yum install man-pages

现在man 2 read正常使用,man2目录下也有相应的东西了。

进入正题,简单讲几个函数,它们的参数变化之多,以后参考手册就完事了。

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

参数解释

  • pathname: 要打开的文件路径。

  • flags: 有可选参数和必选参数两项。

    • 必选: O_RDONLY、O_WRONLY、O_RDWR三项之一。就是打开的权限为只读,只写,可读可写。
    • 可选: 可选就多了,诸如O_CREAT,O_APPEND等,查手册看功能即可。
  • mode是文件创建时候的默认权限有关的参数: 只有当第二个参数中有O_CREAT参数才会发挥作用,默认权限计算方法为:

    mode & (~umask)

返回值

  • 打开成功,返回相应的文件描述符。
  • 打开失败,返回-1并使errno置为这次的错误。

read函数

头文件以及函数原型:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

在man手册中解释的很清楚:

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

从文件描述符fd中读取count个字节到buf中。

参数解释

  • fd: 要读取的文件描述符。
  • buf: 读到的数据放到这个buf中。
  • count: 要读取的字节数。

返回值:

  • 读取成功返回这次读到的字节数。
  • 读取完毕返回0.
  • 读取失败,返回-1,并且errno置为这次的错误。注意当读取模式是非阻塞的时候,会返回-1,errno为EAGAIN。

write函数

头文件以及函数原型:

#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);

同样的,手册解释的很清楚:

write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

write函数从buf中读取count个字节到fd指向的文件中去。

参数解释

  • fd: 打开的文件描述符。
  • buf: 从这个buf中读取数据。
  • count: 要读取的字节数。

返回值

  • 成功写入返回写入的字节个数。
  • 返回0表示没有数据可写。
  • 写失败返回-1,errno被置为此次错误。
原文地址:https://www.cnblogs.com/love-jelly-pig/p/10042529.html