C语言文件复制

不应对非文本文件使用fgetc等易受干扰的函数,建议用fread,fwrite读写二进制
 
 
#include "stdio.h"

/* 保护硬盘,绝对不要一个字节一个字节复制 */
#define SIZEOFBUFFER 256*1024L /* 缓冲区大小,默认为256KB */

long filesize(FILE *stream)
{
	long curpos, length;
	curpos = ftell(stream);
	fseek(stream, 0L, SEEK_END);
	length = ftell(stream);
	fseek(stream, curpos, SEEK_SET);
	return length;
}

int copyfile(const char* src,const char* dest)
{
    FILE *fp1,*fp2;
    int fsize,factread;
    static unsigned char buffer[SIZEOFBUFFER];

    fp1=fopen(src,"rb");
    fp2=fopen(dest,"wb+");
    if (!fp1 || !fp2) return 0;
    for (fsize=filesize(fp1);fsize>0;fsize-=SIZEOFBUFFER)
    {
        factread=fread(buffer,1,SIZEOFBUFFER,fp1);
        fwrite(buffer,factread,1,fp2);
    }
    fclose(fp1);
    fclose(fp2);
    return 1;
}

int main()
{
    copyfile("file1.txt","file2.txt");
    return 0;
}
 

你可能感兴趣的:(C语言,C语言文件复制)