File copy (application of file pointer)

Application of file pointers;

Open files (fopen) and close files (fclose);

Character input function (fgetc) and character output function (fputc);

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

//文件拷贝
int main()
{
	//打开文件
	FILE* pfread = fopen("test1.txt", "r");	//以只读方式打开待拷贝文件
	if (pfread == NULL)
	{
		perror("Open the file of read");
		return 1;
	}
	FILE* pfwrite = fopen("test2.txt", "w");//以只写方式打开待写文件
	if (pfwrite == NULL)
	{
		perror("Open the file of write");
		fclose(pfread);		//如果待写文件打开失败,会退出程序,在退出程序前需要关闭最先打开的待拷贝文件
		pfread = NULL;
		return 1;
	}
	//使用文件
		//拷贝文件
	int ch = 0;
	while ((ch = fgetc(pfread)) != EOF)		//fgetc函数读取文件结束或读取文件失败会返回EOF
	{
		fputc(ch, pfwrite);
	}
	if (ferror(pfread))			//fgetc因读取文件失败结束
		printf("%s\n","I/O error when reading");
	else if (feof(pfread))		//fgetc因遇到文件结尾而结束
		printf("%s\n","End of file reached successfully");
	//关闭文件
	fclose(pfread);
	pfread = NULL;
	fclose(pfwrite);
	pfwrite = NULL;
	return 0;
}

 

 

 The contents of the file test1.txt are completely copied to the file test2.txt.

Guess you like

Origin blog.csdn.net/libj2023/article/details/131733216