linux的常用操作——read函数和write函数

1 read函数

\qquad 返回值:-1:读取失败;0:表示文件读完;>0:读取的字节数
\qquad 参数:第一个参数:要读取文件的文件描述符;第二个参数:存取的地址;第三个参数:存取的字节数大小

2 write函数

\qquad 返回值:-1:写入失败;字节数返回:写入成功。
\qquad 参数:第一个参数:要写入文件的文件描述符;第二个参数:地址,从这个地址写入到文件;第三个参数:空间大小

3 举例
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
        int open_h1_fd;
        int open_h2_fd;
        int close_h1_fd;
        int close_h2_fd;
        int read_fd;
        int write_fd;
        char buf[2048]={0};
        //1.打开h1.txt 和 h2.txtx
        open_h1_fd = open("h1.txt",O_RDONLY);
        if(open_h1_fd==-1){
                perror("h1 open fail");
                exit(1);
        }
        open_h2_fd = open("h2.txt",O_WRONLY);
        if(open_h2_fd==-1){
                perror("h2 open fail");
                exit(1);
        }
        //2.读取h1.txt的内容
        read_fd = read(open_h1_fd,buf,sizeof(buf));
        if(read_fd==-1){
                perror("read fail");
                exit(1);
        }
        //3.将读取的内容写入h2.txt
        write_fd = write(open_h2_fd,buf,sizeof(buf));
        if(write_fd==-1){
                perror("write fail");
                exit(1);
        }
        else{
                printf("write success!\n");
        }
        //4.关闭 h1.txt 和 h2.txt
        close_h1_fd = close(open_h1_fd);
        if(close_h1_fd==-1){
                perror("h1 close fail");
                exit(1);
        }
        else if(close_h1_fd==0){
                printf("h1 close success!\n");
        }
        close_h2_fd = close(open_h2_fd);
        if(close_h2_fd==-1){
                perror("h2 close fail");
                exit(1);
        }
        else if(close_h2_fd==0){
                printf("h2 close success!\n");
        }
        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值