#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
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 main(int argc, char *argv[])
{
char *file1=argv[1];
char *file2=argv[2];
int a,b,num;
FILE *fread_open,*fwrite_open;
fread_open=fopen(argv[1],"r+");//打开文件
num=filesize(fread_open);//获取文件大小,当做缓冲区的大小
char buf[num];
if (!fread_open)
{
printf("read fopen error\n");
exit(1);
}
a=fread(buf,sizeof(char),num,fread_open);//读取文件内容到缓冲区
if (!a)
{
printf("fread error\n");
exit(1);
}
fwrite_open=fopen(argv[2],"w+");//打开目标文件
if (!fwrite_open)
{
printf("write open error\n");
exit(1);
}
b=fwrite(buf,sizeof(char),a,fwrite_open);//把缓冲区里的写入到文件
if (!b)
{
printf("fwrite error\n");
exit(1);
}
printf("success\n");
fclose(fread_open);
fclose(fwrite_open);
return 0;
}
一些fread和fwrite函数可以自行查资料
参考:http://www.cnblogs.com/witxjp/archive/2011/03/21/1990519.html
http://blog.csdn.net/sky_qing/article/details/12783045
至于fprintf和fwrite区别:
fscanf和fpintf是一对,用fprintf写的必须用fscanf来读。
fread和fwrite是一对,用fwrite写的必须用fread来读。
同样的数据,使用fprintf和fwrite写下去的是不一样的,但是使用其相应的读命令读上来的数据会是一样的。
参考:http://blog.chinaunix.net/uid-22588531-id-1772480.html
http://blog.sina.com.cn/s/blog_77e818f40101ac5f.html
ftell:用于得到文件位置指针当前位置相对于文件首的偏移字节数。
fseek:用于二进制方式打开的文件,移动文件读写指针位置
参考:http://www.cnblogs.com/bamboo-talking/archive/2011/04/06/2006592.html