編寫一個程序,用系統/標準IO提供的函數接口,實現文件的拷貝

更多資料請點擊:我的目錄
本篇僅用於記錄自己所學知識及應用,代碼仍可優化,僅供參考,如果發現有錯誤的地方,儘管留言於我,謝謝。

做法1 :系統IO:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{	
	//檢驗輸入參數是否有三位
	if(argc != 3)
	{
		perror("輸入錯誤!\n");
		exit(0);
	}

	//系統IO打開一個指定文件並獲得文件描述符(成功返回大於等於0的整數),或創建一個新文件
	int src = open(argv[1], O_RDONLY);	//argv[1]爲用戶輸入參數所指的文件,O_RDONLY(以只讀方式打開文件)
	if ( src == -1 )			//失敗返回-1
	{
		perror("打開源文件失敗!\n");
		exit(0);
	}

	int dst = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0644);	//argv[2]爲用戶輸入參數所指的文件,
	if( dst == -1 )											//O_WRONLY(以只寫方式打開文件)、
	{														//O_CREAT(如文件不存在則創建)、
		perror("打開目標文件失敗!\n");						//O_TRUNC(如文件存在則清空原有數據)
		exit(0);											//0644 (爲創建文件時制定其權限)
	}

	//創建一塊佔100字節的內存
	char *buf = calloc(1,100);				
	
	while(1)
	{
		//系統IO從指定文件中讀取數據,返回實際讀到的字節數
		int n = read(src, buf, 100);	
		if( n == 0 )
		{
			printf("複製完成!\n");
			break;
		}
		if( n == -1 )//讀取失敗返回-1
		{
			printf("讀取錯誤!\n");
			break;
		}
		char *tmp = buf;
		if( n > 0 )
		{
			//系統IO將數據寫入指定的文件
			int m = write(dst, tmp, n);
			n -= m;
			tmp += m; 
		}
	}	
	close(src);//系統IO關閉文件並釋放相應的資源
	close(dst);
	free(buf);//釋放內存
	return 0;
}

做法2 :標準IO:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char **argv)
{
	//判斷輸入參數是否正確
	if(argc != 3)
	{
		perror("輸入錯誤!\n");
		exit(0);
	}

	//標準IO獲取指定文件的文件指針,r(以只讀方式打開文件,要求文件必須存在)
	FILE * src = fopen (argv[1],"r");
	if(src == NULL)		//打開失敗返回NULL
	{
		perror("打開源文件失敗!\n");
		exit(0);
	}

	//w(以只寫方式打開文件,如文件不存在則創建,如文件存在則清空原有數據)
	FILE * dst = fopen (argv[2],"w");
	if(dst == NULL)		//打開失敗返回NULL
	{
		perror("打開目標文件失敗!\n");
		exit(0);
	}

	//創建五塊佔20字節的內存
	char *buf = calloc(5,20);
	long a,b;
	
	while(1)
	{	
		//ftell()獲取指定文件的當前位置偏移量
		a = ftell(src);
		
		//fread()從指定文件讀取若干個數據塊
		int n = fread(buf, 20, 5, src);
		if(n == 5)
		{
			//fwrite()將若干塊數據寫入指定的文件
			if(fwrite(buf, 20, n, dst) !=n)
			{
				perror("寫入目標文件失敗!\n");
				break;
			}
		}
		else
		{
			if(feof(src)) //feof()判斷一個文件是否到達文件末尾
			{		
				b = ftell(src);
				if(fwrite(buf, b-a, 1, dst) != 1)
				{
					perror("寫入目標文件失敗\n");
					break;
				} 
				printf("文件拷貝成功!\n");
				break;
			}
			if(ferror(src))
			{
				perror("寫入目標文件失敗!\n");
				break;
			}
		}		
	}
	fclose(src);//標準IO關閉文件並釋放相應的資源
	fclose(dst);
	free(buf);//釋放內存
	return 0;
}

更多資料請點擊:我的目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章