C语言—二进制和文本文件的备份
学习参考:
https://www.cnblogs.com/jackytang/p/9011127.html
代码:
#include <stdio.h>
#include <stdlib.h>
int copyFile(char *fileRead, char *fileWrite);
int main() {char fileRead[100]; // 要复制的文件名char fileWrite[100]; // 复制后的文件名// 获取用户输入printf("要复制的文件:");scanf("%s", fileRead);printf("将文件复制到:");scanf("%s", fileWrite);// 进行复制操作if (copyFile(fileRead, fileWrite)) {printf("恭喜你,文件复制成功!\n");}else {printf("文件复制失败!\n");}system("pause");return 0;
}
/**
* 文件复制函数
* @param fileRead 要复制的文件
* @param fileWrite 复制后文件的保存路径
* @return int 1: 复制成功;2: 复制失败
**/
int copyFile(char *fileRead, char *fileWrite) {FILE *fpRead; // 指向要复制的文件FILE *fpWrite; // 指向复制后的文件int bufferLen = 1024 * 4; // 缓冲区长度char *buffer = (char*)malloc(bufferLen); // 开辟缓存int readCount; // 实际读取的字节数if ((fpRead = fopen(fileRead, "rt")) == NULL || (fpWrite = fopen(fileWrite, "wt")) == NULL) {printf("Cannot open file!\n");}// 不断从fileRead读取内容,放在缓冲区,再将缓冲区的内容写入fileWritewhile ((readCount = fread(buffer, 1, bufferLen, fpRead)) > 0) {fwrite(buffer, readCount, 1, fpWrite);}free(buffer);fclose(fpRead);fclose(fpWrite);return 1;
}
测试截图:
具体的内容随便输入!!!