文件操作使用的函数(下)

拷贝文件函数包含了很多文件操作的函数。参考代码理解函数如何使用。

#include< stdio.h>
#include<stdlib.h>
#include< string.h>
int main()
{
	FILE *fp_from = NULL;//定义文件指针
	fopen_s(&fp_from, "from.txt", "w+");
	FILE *fp_to = NULL;
	fopen_s(&fp_to, "to.txt", "w+");

	int len;//获取文件长度
	char*ch = NULL;//缓存buffer

	if ((fp_from ) == NULL)//打开源文件,注意这句话中的括号,“==”的右边要用括号括起来
	{
		printf("open from file error!\n");
		exit(0);
	}
	else
	{
		printf("open from file?successfully!\n?prepareto?write...\n");
	}
	fwrite("hello the world", 1, strlen("hello the world"), fp_from);//将一个字符串写入源文件中
	printf("write successfully!\n\n");

	fflush(fp_from);//刷新文件
	if ((fp_to) == NULL)//打开目标文件
	{
		printf("open write file error!");
		exit(0);
	}
	else
	{
		printf("open?write file successfully!\n");
	}
	len = ftell(fp_from);//获取源文件长度

	ch = (char *)malloc(sizeof(char*)*(len)); //动态分配数组长度

	//memset(ch, 0, len); //清零,否则无法将内容写入!!!

	rewind(fp_from);//将源文件指针复位到开头,否则写入为空!
	fread(ch, 1, len, fp_from);//将源文件内容写到buffer中
	fwrite(ch, 1, len, fp_to); //将buffer中的内容写回到目标文件中
	printf("copy?successfully!\n");
	fclose(fp_from);//关闭文件
	fclose(fp_to);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43079376/article/details/84000677