Linux系统调用三、read()函数和write()函数介绍


在这里插入图片描述


❀1. read函数

  • 包含头文件
#include <unistd.h>
  • 函数原型
ssize_t read(int fd, void *buf, size_t count);
  • 函数功能

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

  • 函数参数

    • fd :文件描述符
    • buf:缓冲区
    • count:缓冲区大小
  • 函数返回值

    • 读取失败返回-1,同时设置errno 。如果非阻塞的情况下返回-1,需要判断errno的值
    • 成功则返回读到的字节数(0表示已经读到文件末尾)

❀2. 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.

  • 函数参数

    • fd :文件描述符
    • buf:缓冲区
    • count:写入的字节数
  • 函数返回值

    • 写入失败返回-1,同时设置errno
    • 写入成功则返回写入的字节数(0表示未写入)

❀3. 使用read和write实现cat命令

/************************************************************
  >File Name  : mcat.c
  >Author     : QQ
  >Company    : QQ
  >Create Time: 2022年05月13日 星期五 12时11分44秒
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define BUF_MAX 512 /*buf缓冲区最大值*/
#define FILE_MAX 5 /*可以查看的最大文件数*/

int main(int argc, char* argv[])
{
	if(argc < 2)
	{
		printf("not fount file name");
		return -1;	
	}
	if(argc - 1 > FILE_MAX)
	{
		printf("too many filenames\n");
		return -1;	
	}
	int i = 0;
	int fd[FILE_MAX];
	char buf[BUF_MAX];
	int read_size = 0;
	memset(buf, 0, BUF_MAX);
	for(i = 0; i < (argc - 1); i++)
	{
		fd[i] = open(argv[1 + i], O_RDONLY);
		read_size = read(fd[i], buf, sizeof(buf));
		write(STDOUT_FILENO, buf, read_size); /*STDOUT_FILENO是标准输出文件描述符1的宏定义*/
	}
	for(i = 0; i < (argc - 1); i++)
	{
		close(fd[i]);
	}
	return 0;
}

功能测试


在这里插入图片描述


posted @ 2022-05-17 17:44  Mindtechnist  阅读(69)  评论(0编辑  收藏  举报  来源