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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM