您的位置:首页 > 其它

从一个文件中读取数据到内存,然后再把内存中的数据写入另外一个文件

2016-03-08 09:12 926 查看
//从一个文件中读取数据到内存,然后再把内存中的数据写入另外一个文件

#include "stdafx.h"
#include <malloc.h>

int filelength(FILE *fp);
int _tmain(int argc, _TCHAR* argv[])
{
FILE *fp = NULL;
FILE *fp2 = NULL;
int FpSize = 0;
fopen_s(&fp,"C:\\Windows\\System32\\notepad.exe","rb");
fopen_s(&fp2, "d:\\CYP.exe", "wb");
FpSize = filelength(fp);

char * FileBuffer = (char *)malloc(FpSize);
if (FileBuffer!=NULL)
{
fread_s(FileBuffer, FpSize + 1, 1, FpSize, fp);

fwrite(FileBuffer, FpSize, 1, fp2);
}
free(FileBuffer);
fclose(fp);
fclose(fp2);

//printf("%d\n", FpSize);
getchar();
return 0;
}

//获取文件大小
int filelength(FILE *fp)
{
int num;
fseek(fp, 0, SEEK_END);
num = ftell(fp);
fseek(fp, 0, SEEK_SET);
return num;
}
//fopen  返回值:文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。
//fseek  int fseek(FILE *stream, long offset, int fromwhere);函数设置文件指针stream的位置
//ftell  函数 ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数。
//fclose 使用fclose()函数就可以把缓冲区内最后剩余的数据输出到内核缓冲区,并释放文件指针和有关的缓冲区。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: