read,write函数

	#include <unistd.h>
	    ssize_t read(int fd, void *buf, size_t count);
	        参数:
	            - fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
	            - buf:需要读取数据存放的地方,数组的地址(传出参数)
	            - count:指定的数组的大小
	        返回值:
	            - 成功:
	                >0: 返回实际的读取到的字节数
	                =0:文件已经读取完了
	            - 失败:-1 ,并且设置errno

    #include <unistd.h>
    ssize_t write(int fd, const void *buf, size_t count);
        参数:
            - fd:文件描述符,open得到的,通过这个文件描述符操作某个文件
            - buf:要往磁盘写入的数据,数组
            - count:要写的数据的实际的大小
        返回值:
            成功:实际写入的字节数
            失败:返回-1,并设置errno
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main() {
    //1.通过open打开txt文件
    int srcfd = open("english.txt", O_RDONLY);
    if(srcfd == -1){
        perror("open");
        return -1;
    }

    //2.创建一个新的文件(拷贝文件)
    int destfd = open("copy.txt", O_WRONLY | O_CREAT, 0664);
    if(destfd == -1){
        perror("open");
        return -1;
    }

    //3.频繁的读写操作
    char buf[1024] = {0};
    int len = 0;
    while((len = read(srcfd, buf, sizeof(buf))) > 0){
        write(destfd, buf, len);
    }

    //4.关闭文件
    close(destfd);
    close(srcfd);
    

    return 0;
}

nowcoder@nowcoder:~/linux/lession10$ ls
copyfile.c  english.txt
nowcoder@nowcoder:~/linux/lession10$ gcc copyfile.c -o copy
nowcoder@nowcoder:~/linux/lession10$ ./copy
nowcoder@nowcoder:~/linux/lession10$ ll
总用量 280
drwxrwxr-x  2 nowcoder nowcoder   4096 3-р с  4 17:30 ./
drwxrwxr-x 12 nowcoder nowcoder   4096 3-р с  4 16:42 ../
-rwxrwxr-x  1 nowcoder nowcoder   8528 3-р с  4 17:30 copy*
-rw-rw-r--  1 nowcoder nowcoder   1659 3-р с  4 17:29 copyfile.c
-rw-rw-r--  1 nowcoder nowcoder 129772 3-р с  4 17:30 copy.txt
-rw-rw-r--  1 nowcoder nowcoder 129772 3-р с  4 16:43 english.txt

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值