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

//用于拷贝文件
#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;

}

posted on 2015-03-08 09:36  weekman  阅读(4808)  评论(0编辑  收藏  举报