#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *sourceFile, *targetFile;
char sourceFileName[100], targetFileName[100];
char ch;
printf("请输入要备份的文件名:");
fgets(sourceFileName, sizeof(sourceFileName), stdin);
// 删除源文件名字符串中的换行符
sourceFileName[strcspn(sourceFileName, "\n")] = 0;
sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("无法打开文件 %s\n", sourceFileName);
exit(1);
}
printf("请输入备份文件名:");
fgets(targetFileName, sizeof(targetFileName), stdin);
// 删除目标文件名字符串中的换行符
targetFileName[strcspn(targetFileName, "\n")] = 0;
targetFile = fopen(targetFileName, "w");
if (targetFile == NULL) {
printf("无法创建文件 %s\n", targetFileName);
fclose(sourceFile);
exit(1);
}
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}
printf("文件备份成功!\n");
fclose(sourceFile);
fclose(targetFile);
return 0;
}
bbbbbbbbbbbbbbb
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFFER_SIZE 4096
int main() {
char sourceFileName[100], targetFileName[100];
char buffer[BUFFER_SIZE];
int sourceFile, targetFile;
ssize_t bytesRead, bytesWritten;
printf("请输入要备份的文件名:");
fgets(sourceFileName, sizeof(sourceFileName), stdin);
// 删除源文件名字符串中的换行符
sourceFileName[strcspn(sourceFileName, "\n")] = 0;
sourceFile = open(sourceFileName, O_RDONLY);
if (sourceFile == -1) {
printf("无法打开文件 %s\n", sourceFileName);
exit(1);
}
printf("请输入备份文件名:");
fgets(targetFileName, sizeof(targetFileName), stdin);
// 删除目标文件名字符串中的换行符
targetFileName[strcspn(targetFileName, "\n")] = 0;
targetFile = open(targetFileName, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (targetFile == -1) {
printf("无法创建文件 %s\n", targetFileName);
close(sourceFile);
exit(1);
}
while ((bytesRead = read(sourceFile, buffer, BUFFER_SIZE)) > 0) {
bytesWritten = write(targetFile, buffer, bytesRead);
if (bytesWritten != bytesRead) {
printf("文件备份失败!\n");
close(sourceFile);
close(targetFile);
exit(1);
}
}
close(sourceFile);
close(targetFile);
printf("文件备份成功!\n");
return 0;
}