Linux系统调用IO--read函数详解

说明:

        本文主要内容是从网上摘录的,并加上模板案例来验证说明。 参考以下文章,谢谢作者的分享:

        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;
}

运行结果展示:

第一行:编译

第二行:运行

 

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值