说明:
本文主要内容是从网上摘录的,并加上模板案例来验证说明。 参考以下文章,谢谢作者的分享:
Linux 系统 IO之 read write 函数_系统iowrite-CSDN博客
目录:
一、read函数的使用意义
read
函数从给定的文件描述符指定的文件中,读取 count个字节的数据,存放至 buf中。
二、open函数使用时需要添加的头文件
#include <unistd.h>
三、 open函数的原型
ssize_t read(int fd, void *buf, size_t count);
四、返回值说明
size_t:无符号整型 <==> unsigned int
ssize_t:有符号整型 <==> int
具体数值说明:
返回 -1:文件读取失败,设置 errno 指出失败原因
返回 0:文件读取结束
返回 >0:本次所成功读取的字节数
五、参数说明和用法
1、形参说明:
int fd:指定要读写的文件描述符
void* buf:缓冲区,一般是一个数组,用于存放读取的内容
size_t count:一次要读取的最大字节数
2、使用模板案例:
说明:以下是一个读取文件内容的APP程序,可以在Linux系统内直接编译和运行
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
/*
* ./read 1.txt
* argc = 2 //参数个数
* argv[0] = "./read" //第一个参数为文件名字 在linux中./read表示当前目的APP程序
* argv[1] = "1.txt" //第二个要读取的文件名字
*/
int main(int argc, char **argv)
{
int fd;
int i;
int len;
unsigned char buf[100]; //缓冲区
//如果输入的参数不是2,则返回-1
if (argc != 2)
{
printf("Usage: %s <file>\n", argv[0]);
return -1;
}
//打开文件
fd = open(argv[1], O_RDONLY);
if (fd < 0)
{
printf("can not open file %s\n", argv[1]);
printf("errno = %d\n", errno);
printf("err: %s\n", strerror(errno));
perror("open");
}
else
{
printf("fd = %d\n", fd);
}
/* 读文件/打印文件内容 */
while (1)
{
len = read(fd, buf, sizeof(buf)-1);
if (len < 0)
{
perror("read");
close(fd);
return -1;
}
else if (len == 0)//读取结束
{
break;
}
else
{
/* buf[0], buf[1], ..., buf[len-1] 含有读出的数据
* buf[len] = '\0'
*/
buf[len] = '\0';
printf("%s", buf);
}
}
close(fd);
return 0;
}
运行结果展示:
第一行:编译
第二行:运行