i.MX6ULL终结者文件IO和标准IO 文件IO write()

本文档展示了如何使用C语言的标准函数read()和write()来实现文件复制。代码示例中,首先打开源文件hello.txt,然后创建并打开目标文件topeet.txt。通过循环读取源文件内容并写入目标文件,实现了文件内容的复制。实验结果显示,源文件的内容成功复制到了topeet.txt中。
摘要由CSDN通过智能技术生成

write():常用来写文件,定义如下:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数含义:
fd: 文件描述符;
buf: 缓存区,存放将要写入的数据;
count: 每次写入的个数。
函数功能:
每次从buf缓存区拿count个字节写入fd文件。
返回值:
大于或等于0表示执行成功,返回写入的字节数;
返回-1代表出错。
实验代码在io/io3.c:路径为:11_Linux系统开发进阶\Linux系统编程_章节使用资料。
复制文件:使用read()度数据到缓存区,再将缓存区内容写到topeet.txt实现文件复制。

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
 
int main(int argc, const char *argv[])
{
    char buf[8]={0};
    size_t rlen,wlen;
    int rfd = open("./hello.txt",O_RDONLY);
    int wfd = open("./topeet.txt",O_CREAT|O_RDWR);
    if(-1 == rfd || -1 == wfd){
        perror("open");
        return -1;
    }
    do{//读取文件内容并写到目标文件
        rlen = read(rfd,buf,sizeof(buf));
        wlen = write(wfd,buf,sizeof(buf));
        printf("%s",buf);
        memset(buf,0,sizeof(buf));
    }while(rlen>0 && wlen >=0);
    printf("\n");
 
    close(rfd);
    close(wfd);
    return 0;
}

编译运行打开topeet.txt :
在这里插入图片描述

图 1

可以看到已经完成了复制。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值