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

本文详细介绍了Linux中的read函数,包括其头文件、函数原型、参数解析、返回值说明,并提供了示例代码。同时强调了read操作完成后及时关闭文件的重要性,以释放系统资源和保障文件安全性。此外,还提到了与文件定位相关的lseek函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
        int fd;

        int n_write;
		int n_read;

        char *buf = "dengerbao zhende henshuai";
		char *readBuf;

        fd = open("./file1",O_RDWR);

        if(fd == -1){//判断open函数是否成功打开指定路径的文件
                printf("open failed!\n");
        }else{
                printf("open success!\n");
        }

//      ssize_t write(int fd, const void *buf, size_t count);
        n_write = write(fd,buf,strlen(buf));
//	使用strlen而不是sizeof的原因:linux下指针占4个字节,64linux则占8个字节,很明显不能用于此
        if(n_write == -1){
                printf("write error!\n");
        }else{
                printf("write %d byte to file\n",n_write);
        }

//		off_t lseek(int fd, off_t offset, int whence);
		lseek(fd,0,SEEK_SET);
//		使用lseek函数让文件读写位置移动到头部,不然读写位置在尾端会导致read函数读取不到数据
		readBuf = (char *)malloc(sizeof(char)*n_write);

		n_read = read(fd,readBuf,n_write);	

		printf("readBuf:%s\n",readBuf);

		lseek(fd,0,SEEK_END);
//		使用lseek函数让文件读写位置重新回到尾部,有始有终
        close(fd);//及时关闭文件,以免多占用资源或损坏文件

        return 0;
}

6.补充 :lseek函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值