文件管理实验:备份文件(C语言和Linux系统调用) 您所在的位置:网站首页 linux复制内容到另一个文件中去了 文件管理实验:备份文件(C语言和Linux系统调用)

文件管理实验:备份文件(C语言和Linux系统调用)

2024-06-09 20:31| 来源: 网络整理| 查看: 265

实验要求

1、利用C语言函数fopen(), fread(), fwrite(), fclose() 来实现简单的文件备份, 即将一个文件的内容拷贝到另一个文件中去。

2、利用Linux操作系统的系统调用函数open(), read(), write(), close() 来实现简单的文件备份, 即将一个文件的内容拷贝到另一个文件中去。

代码

c语言

#include #include #include 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 #include #include #include #include #include #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); } }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有