//從一個文件中讀取數據到內存,然后再把內存中的數據寫入另外一個文件 #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()函數就可以把緩沖區內最后剩余的數據輸出到內核緩沖區,並釋放文件指針和有關的緩沖區。