实验要求
1、利用C语言函数fopen(), fread(), fwrite(), fclose() 来实现简单的文件备份, 即将一个文件的内容拷贝到另一个文件中去。
2、利用Linux操作系统的系统调用函数open(), read(), write(), close() 来实现简单的文件备份, 即将一个文件的内容拷贝到另一个文件中去。
代码
c语言
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define BUF_SIZE 4096
#define src_path "12.exe"
#define dst_path "22.exe"
int main(void) {
char buf[BUF_SIZE];
FILE *source, *backup;
long long ret;
clock_t start, end;
double time;
source = fopen(src_path, "rb");
backup = fopen(dst_path, "wb");
if (!source) {
printf("Error in opening file.\n");
exit(1);
}
if (!backup) {
printf("Error in creating file.\n");
exit(1);
}
// 备份
start = clock(); // 开始计时
int t = 0;
while (fread(buf, BUF_SIZE, 1, source) == 1) {
fwrite(buf, BUF_SIZE, 1, backup);
t++;
}
fseek(source, BUF_SIZE*t, SEEK_SET); // 重定位
ret = fread(buf, 1, BUF_SIZE, source);
fwrite(buf, 1, ret, backup);
end = clock(); // 结束计时
if (fclose(source)) {
printf("Error in close file:source.\n");
exit(1);
}
if (fclose(backup)) {
printf("Error in close file:backup.\n");
exit(1);
}
time = (double(end - start) / CLOCKS_PER_SEC);
printf("运行时间:%f s\n", time);
}
Linux操作系统
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUF_SIZE 10240
#define src_path "12.exe"
#define dst_path "22.exe"
int main(void) {
char buf[BUF_SIZE];
int source, backup;
long long ret;
source = open(src_path, 0);
backup = open(des_path, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
if (source == -1) {
printf("Error in opening file.\n");
exit(1);
}
if (backup == -1) {
printf("Error in creating file.\n");
exit(1);
}
// 备份
while((ret = read(source, buf, BUF_SIZE)) != 0){
if(ret == -1){
printf("Error in reading file.\n");
exit(1);
}
int status = write(backup, buf, ret);
if(status == -1){
printf("Error in writing file.\n");
exit(1);
}
}
if(close(source) == -1){
printf("Close error.\n");
exit(1);
}
if(close(backup) == -1){
printf("Close error.\n");
exit(1);
}
}