文件管理實驗:備份文件(C語言和Linux系統調用)

實驗要求

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);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章