1 #include <stdio.h> 2 3 int main(int argc,char *argv) 4 { 5 //以只讀的方式打開被複制的文件 6 FILE *srcFd = fopen("./source.txt","r"); 7 if(NULL == srcFd) 8 { 9 printf("open source file failed\n"); 10 return -1; 11 } 12 13 //以讀寫的方式建立一個不存在的文件 14 FILE *dstFd = fopen("./save.txt","w+"); 15 if(NULL == dstFd) 16 { 17 printf("open save file failed\n"); 18 return -1; 19 } 20 21 //進行獲取文件大小的操做 22 fseek(srcFd,0,SEEK_END); //將光標移動到文件末尾 23 long fileSize = ftell(srcFd); //獲取文件的大小 24 fseek(srcFd,0,SEEK_SET); //將光標恢復到文件的開頭 25 26 //開闢一個新空間(動態開闢) 27 char *dataBuf = (char *)calloc(1,fileSize+1); 28 if(NULL == dataBuf) 29 { 30 printf("calloc a memory failed\n"); 31 return -1; 32 } 33 34 //讀取文件的內容 35 long retSize = fread(dataBuf,1,fileSize,srcFd); 36 if(retSize != fileSize) 37 { 38 printf("read file context failed\n"); 39 return -1; 40 } 41 42 //寫入保存文件中 43 retSize = fwrite(dataBuf,1,fileSize,dstFd); 44 if(retSize != fileSize) 45 { 46 printf("write context in file failed\n"); 47 return -1; 48 } 49 50 //關閉文件和釋放內存空間 51 fclose(srcFd); 52 fclose(dstFd); 53 54 free(dataBuf); 55 56 return 0; 57 }