Linux文件学习之read函数和读出操作

一、read函数:

1.函数包含头文件:

#include <unistd.h>

2.函数原型:

ssize_t read(int fd, void *buf, size_t count);

3.函数参数:

fd——文件描述符

buf——一块指定的内存空间

count——指定的要读取的字节数

4.函数返回值:
成功返回读取的字节数,出错返回 -1并设置 errno,如果在调read之前已到达文件末尾,则这次read返回0

注意 :对文件操作完之后要及时的close文件,为了 :①更早的释放所占用的系统资源 ②更早的将文件置于更安全的状态

5.demo

#include <stdio.h>
#include <sys/types.h>
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件的程序: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #define FIFO_PATH "/tmp/fifo" int main() { char buf[1024]; int fd; pid_t pid; if (access(FIFO_PATH, F_OK) == -1) { if (mkfifo(FIFO_PATH, 0666) == -1) { perror("mkfifo"); exit(EXIT_FAILURE); } } printf("Waiting for the writer ...\n"); if ((fd = open(FIFO_PATH, O_RDONLY)) == -1) { perror("open"); exit(EXIT_FAILURE); } printf("Reading ...\n"); while (1) { ssize_t n = read(fd, buf, sizeof(buf)); if (n == -1) { perror("read"); exit(EXIT_FAILURE); } else if (n == 0) { printf("Writer closed the pipe\n"); exit(EXIT_SUCCESS); } else { printf("%s", buf); } } close(fd); exit(EXIT_SUCCESS); } ``` 写文件的程序: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #define FIFO_PATH "/tmp/fifo" int main() { char buf[1024]; int fd; if (access(FIFO_PATH, F_OK) == -1) { if (mkfifo(FIFO_PATH, 0666) == -1) { perror("mkfifo"); exit(EXIT_FAILURE); } } printf("Enter the content to write: "); fgets(buf, sizeof(buf), stdin); if ((fd = open(FIFO_PATH, O_WRONLY)) == -1) { perror("open"); exit(EXIT_FAILURE); } ssize_t n = write(fd, buf, sizeof(buf)); if (n == -1) { perror("write"); exit(EXIT_FAILURE); } close(fd); exit(EXIT_SUCCESS); } ``` 这两个程序采用的是阻塞式的管道模式。读文件的程序会一直阻塞在 `read` 函数上,直到有数据可读,而写文件的程序会一直阻塞在 `write` 函数上,直到数据被写入管道中。需要注意的是,在使用管道时,写入数据的大小不能超过管道的缓冲区大小,否则会导致写入失败或者读取不完整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值