c语言中实现文件内容的复制

41 篇文章 0 订阅

c语言中实现文件内容的复制

思路:

1.先创建一个新文件
2.打开有内容的已存在文件
3.创建一个buf,将旧文件的内容写入buf中
4.再将buf中的内容写入新文件中,写入新文件的过程中,最好使用循环,否则如果buf不够会复制不全。

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <stdlib.h>
#include<unistd.h>

int main()
{
        int fp2 = open("file2", O_RDWR | O_CREAT,0777);/*先创建一个新文件 */
        if(fp2 == -1)
        {
                perror("tips:");/*提示信息 */

        }
        printf("fp2 = %d\n",fp2);
        int fp1 = open("file1",O_RDWR,0777);/*打开已存在的文件 */
        if(fp1 == -1)
        {
                perror("tips:");
                exit(1);
        }
        printf("fp1 = %d\n",fp1);

        char buf[2048] = {110};/*创建一个缓冲区 */
        int fr = read(fp1,buf,sizeof(buf));
        if(fr == -1)
        {
                perror("tips:");
                exit(1);
        }
        while(fr)/*实现循环写和读操作 */
        {
                int fw = write(fp2,buf,fr);
                printf("fw = %d\n",fw);
                fr =read(fp1,buf,sizeof(buf));/*继续下一次读操作*/
        }
        int fc1 = close(fp1);
        int fc2 = close(fp2);/*最后关闭文件*/
        printf("fc1 = %d,fc2 = %d\n",fc1,fc2);

}
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值