首页 > 编程语言 > 详细

c语言文件操作——复制文件

时间:2015-03-08 10:22:10      阅读:253      评论:0      收藏:0      [点我收藏+]

//用于拷贝文件
#include <stdio.h>
#include<stdlib.h>
#include <string.h>

int main()
{
    FILE *fp_from=NULL;            //定义文件指针
    FILE *fp_to=NULL;
    int len;                            //获取文件长度
    char *ch=NULL;            //缓存buffer

    if ((fp_from=fopen("from.txt","w+"))==NULL)        //打开源文件,注意这句话中的括号,“==”的右边要用括号括起来
    {
        printf("open from file error!\n");
        exit(0);
    }
    else
    {
        printf("open from file successfully! prepare to write...\n");
    }

    fwrite("hello",1,strlen("hello"),fp_from);                //将一个字符串写入源文件中
    printf("write successfully!\n\n");
    fflush(fp_from);                                        //刷新文件

    if ((fp_to=fopen("to.txt","w+"))==NULL)                //打开目标文件
    {
        printf("open write file error!");
        exit(0);
    }
    else
    {
        printf("open write file successfully!\n");
    }

    len=ftell(fp_from);                //获取源文件长度
    ch=(char *)malloc(sizeof(char *)*(len));                //动态分配数组长度
    memset(ch,0,len);                            //清零,否则无法将内容写入!!!

    rewind(fp_from);                            //将源文件指针复位到开头,否则写入为空!
    fread(ch,1,len,fp_from);                //将源文件内容写到buffer中
    
    fwrite(ch,1,len,fp_to);                    //将buffer中的内容写回到目标文件中

    printf("copy successfully!\n");        
    fclose(fp_from);                            //关闭文件
    fclose(fp_to);

    return 0;

}

c语言文件操作——复制文件

原文:http://www.cnblogs.com/weekman/p/4321327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!