栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


文章目录
    • ❀1. read函数
    • ❀2. write函数
    • ❀3. 使用read和write实现cat命令


❀1. read函数
  • 包含头文件
#include 
  • 函数原型
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 
  • 函数原型
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命令
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUF_MAX 512 
#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 filenamesn");
		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); 
	}
	for(i = 0; i < (argc - 1); i++)
	{
		close(fd[i]);
	}
	return 0;
}

功能测试



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号