天天看點

六、C語言實作文本檔案和二進制檔案的拷貝

六、C語言實作文本檔案和二進制檔案的拷貝

1、代碼實作

#include<stdio.h>
#include<assert.h>

//文本檔案拷貝
void TxtFileCopy(FILE* des, FILE* arc)
{
	assert(arc != NULL);//添加斷言==if(arc==NULL) printf("源檔案不存在,無法讀取");

	while (1)
	{
		char ch = fgetc(arc);

		if (ch == EOF) break;
		
		fputc(ch, des);
	}
	printf("拷貝成功!\n");

	fclose(arc);
	fclose(des);
}

//二進制檔案拷貝
void  BinaryFileCopy(FILE* des, FILE* arc)
{
	assert(arc != NULL);

	char buffer[10];

	int tmp=0;
	//注意:fread()的傳回值
	while ((tmp = fread(buffer, sizeof(char), 10, arc))!=0)
	{
		fwrite(buffer, sizeof(char), 10, des);
	}

	printf("拷貝成功\n");
	fclose(arc);
	fclose(des);

}


int main()
{
	/*FILE* fp = fopen("D:\\text.txt", "r");
	FILE* fw = fopen("D:\\text1.txt", "w");
	TxtFileCopy(fw, fp);//文本檔案拷貝*/

	FILE* fp = fopen("D:\\jay.mp3", "rb");
	FILE* fw = fopen("D:\\1.mp3", "wb");
	BinaryFileCopy(fw, fp);//二進制檔案拷貝

	return 0;
}
           

2、測試結果

  1. 文本檔案
    六、C語言實作文本檔案和二進制檔案的拷貝
    六、C語言實作文本檔案和二進制檔案的拷貝
  2. 二進制檔案(這裡使用傑倫的一首歌.mp3檔案)
    六、C語言實作文本檔案和二進制檔案的拷貝
六、C語言實作文本檔案和二進制檔案的拷貝
六、C語言實作文本檔案和二進制檔案的拷貝

3、總結

  • 多注意文本檔案和二進制檔案的差別
  • 注意在使用fread()函數時的傳回值
  • 六、C語言實作文本檔案和二進制檔案的拷貝

繼續閱讀