Linux read/write函数

Linux read/write函数

read函数

头文件
#include <unistd.h>
函数签名
ssize_t read(int fd, void *buf, size_t count);
参数

fd:int类型,要读取的文件的文件描述符;
*buf: void*类型,存放读取的字符;
count:想要读取的字节总数;

Return Value

On success
返回读到的字节数(如果小于 count,说明提前到达了文件末尾);
如果到达文件末尾,返回 0;
On error
-1 is returned, and errno is set appropriately;

示例
const char *path = "./test.txt";
int fd = open(*path, O_RDONLY);
char buf[1024];
int count = 10;
int rsize = read(fd, buf, count);
close(fd);

write函数

函数签名
ssize_t write(int fd, const void *buf, size_t count);
参数

fd:int类型,要读取的文件的文件描述符;
*buf: const void*类型,要写入的字符;
count:将要写入的字节总数;

Return Value

On success
返回写入的字节数(小于 count,说明磁盘空间满了);
如果没有写入任何内容,返回 0;
On error
-1 is returned, and errno is set appropriately;

示例
const char *path = "./test.txt";
int fd = open(*path, O_RDWR);// 读写
//int fd = open(*path, O_WRONLY);// 只写
const char buf[] = "Hello World";
int count = sizeof(buf);
int wsize = read(fd, buf, count);
close(fd);

读写完整示例

myrdwr.c

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char* argv[]){
    // 以读写的方式打开文件,不存在则创建
    const char* path = "./test.txt";
    int fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0664);
    if(fd == -1){
        perror("Open Error");
        return 0;
    }
    // read
    char buf[1024];
    int count = 1024;
	int rsize;
	while(rsize = read(fd, buf, count)){
		if(rsize == -1){
        	perror("Read Error");
        	return 0;
    	}
    	printf("count = %d\n", count);
    	printf("the number of bytes read is %d\n", rsize);
    	printf("%s\n", buf);
	}
    // write
    const char w_buf[] = "Hello, my name is Lucrezia.\n";
    count = sizeof(w_buf);
    int wsize = write(fd, w_buf, count);
    if(wsize == -1){
        perror("Write Error");
        return 0;
    }
    printf("count = %d\n", count);
    printf("the number of bytes written is %d\n", wsize);
    printf("%s\n", w_buf);
    close(fd);
    return 0;
}

makefile
https://blog.csdn.net/m0_46216098/article/details/107534978

运行结果
指令
luxurylu@luxurylu-virtual-machine:~/pointer22/0721$ ls
luxurylu@luxurylu-virtual-machine:~/pointer22/0721$ make
luxurylu@luxurylu-virtual-machine:~/pointer22/0721$ ./myrdwr 
luxurylu@luxurylu-virtual-machine:~/pointer22/0721$ cat test.txt 
截图

在这里插入图片描述

2020/07/23 14:05
@luxurylu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值