0
点赞
收藏
分享

微信扫一扫

Linux read()、write()函数

穿裙子的程序员 2022-04-27 阅读 79
linux

介绍

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

read()函数

头文件和函数原型

   #include <unistd.h>

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

参数

返回值

 实例

/*
读取文件数据,返回读取的字节数据值
*/
#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()、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);
     }
  }
}

 

举报

相关推荐

0 条评论