Linux read()、write()函数

介绍

        read()函数用来读取打开文件的数据;write()函数将数据写入一个已打开的文件中。

read()函数

头文件和函数原型

   #include <unistd.h>

   ssize_t read(int fd, void *buf, size_t count);
   // ssize_t 是有符号整数类型;size_t是无符号整数类型

参数

fd:        文件描述符(文件名或文件路径)

buf:      存放输入数据的内存缓冲区地址

count:   指定最多能读取的字节数

返回值

读取成功:返回的是读取到的字节数

读取到文件尾:0

读取失败:-1

 实例

/*
读取文件数据,返回读取的字节数据值
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1024
int main(int argc,char *argv[]){
        //argc表示输入命令参数的个数,*argv[]代表每个命令的值
        //如命令为 ./read  file.txt
        //则 argv[0]---> ./read
        //   argv[1]----> file,txt
        int fd;
        char buf[SIZE]; //设置缓冲区大小
        if (argc < 2){  //输入命令是否正确
          perror("Input './a.out filename'");
          exit(1);
        }
        fd = open(argv[1],O_RDONLY | O_CREAT,0664); //打开文件,没有就创建
        if (fd == -1){
           perror("Open error");
           exit(1);
        }
        int count = read(fd,buf,sizeof(buf));   //读取大小最多为sizeof(buf)大的文件数据
        printf("The %s size is %d\n",argv[1],count);
        close(fd);
}

write()函数

头文件与函数原型

 #include <unistd.h>

 ssize_t write(int fd, const void *buf, size_t count);

参数

与read()函数类似

fd:        文件描述符(文件名或文件路径)

buf:      要写入文件中数据的内存地址

count:  buf 写入文件的数据字节数

返回值

写入成功:     返回 实际写入的字节数    

写入失败:-1

read()、write()函数的使用

// 利用write() 、read()函数实现复制文件
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define SIZE 1024
int main(int argc,char *argv[]){
     int fd,fd1,count,count1;
     char buf[SIZE];
     //打开要读取数据的文件
     fd = open(argv[1],O_RDONLY);
     if(fd == -1){
        perror(argv[1]);
        exit(1);
     }
     //打开放置读取数据的文件,没有就创建文件
     fd1 = open(argv[2],O_WRONLY | O_CREAT,0664);
     if(fd1 == -1){
        perror(argv[2]);
        exit(1);
     }
     while (count > 0){
     count = read(fd,buf,sizeof(buf));
     if (count == -1){
        perror("Read data error");
        exit(1);
     }
     count1 = write(fd1,buf,count);
     if (count1 == -1){
        perror("Write data error");
        exit(1);
     }
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值