2025年4月10日 星期四 乙巳(蛇)年 正月十一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

read与write

时间:03-29来源:作者:点击数:37

函数原型

  1. ssize_t read(int filedes, void *buf, size_t count);
  2. ssize_t write(int filedes, void* buf, size_t count);

功能

read函数从打开的设备或文件中读取数据。

函数向打开的设备或文件中写数据。

头文件

  • #include <unistd.h>

返回值

  返回值:成功返回写入或读取的字节数count,出错返回-1并设置errno写常规文件时。而write的返回值通常等于请求写的字节数

  • count,而向终端设备或网络写则不一定。

说明

(1)filedes:文件描述符;

(2)buf:待写入或读取数据缓存区;

(3)count:要写入或读取的字节数;

例:

  • #include <unistd.h>
  • #include <stdlib.h>
  • int main(void)
  • {
  • char buf[10];
  • int n;
  • n = read(STDIN_FILENO, buf, 10);
  • if (n < 0) {
  • perror("read STDIN_FILENO");
  • exit(1);
  • }
  • write(STDOUT_FILENO, buf, n);
  • return 0;
  • }
  • #include <unistd.h>
  • #include <fcntl.h>
  • #include <errno.h>
  • #include <string.h>
  • #include <stdlib.h>
  • #define MSG_TRY "try again\n"
  • int main(void)
  • {
  • char buf[10];
  • int fd, n;
  • fd = open("/dev/tty", O_RDONLY|O_NONBLOCK);
  • if(fd<0) {
  • perror("open /dev/tty");
  • exit(1);
  • }
  • tryagain:
  • n = read(fd, buf, 10);
  • if (n < 0) {
  • if (errno == EAGAIN) {
  • sleep(1);
  • write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY));
  • goto tryagain;
  • }
  • perror("read /dev/tty");
  • exit(1);
  • }
  • write(STDOUT_FILENO, buf, n);
  • close(fd);
  • return 0;
  • }

注:

1.注意返回值类型是ssize_t,表示有符号的size_t,这样既可以返回正的字节数、0(表示到达文件末尾)也可以返回负值-1(表示出错)。

2.使用read,write操作管道,FIFO以及某些设备时,特别是终端,网络和STREAMS,有下列两种性质。

a.一次read操作所返回的数据可能少于所要求的数据,即使还没达到文件尾端也可能是这样。这不是一个错误,应该继续读该设备。

b.一次write操作的返回值也可能少于指定输出的字节数。这也不是错误,应当继续写余下的数据至该设备。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
上一篇:fwrite与fread 下一篇:memset函数使用
推荐内容
相关内容
栏目更新
栏目热门