我想用开辟堆空间实现拷贝操作,但程序不知道错在哪
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int Cfile(char* p, char* filename)
{
FILE* pf = fopen(filename, "r");
if (pf == NULL)
{
perror("fopen");
return -1;
}
//使用文件
int temp = 1024;
int i = 0;
while (fread(p + i, sizeof(char), 1, pf))
{
if (i == temp-1)
{
char* p1 = (char*)realloc(p, sizeof(char) * (temp + 1024));
if (p1 != NULL)
{
p = p1;
p1 = NULL;
temp += 1024;
printf("增容成功\n");
}
else
{
printf("增容失败\n");
perror("realloc");
return -1;
}
}
i++;
}
//关闭文件
fclose(pf);
pf = NULL;
return i;
}
void Vfile(char* p, char* filename,int n)
{
FILE* pf = fopen(filename, "w");
if (pf == NULL)
{
perror("fopen");
return -1;
}
//使用文件
for (int i = 0;i < n;i++)
{
fwrite(p+i, sizeof(char), 1, pf);
}
//关闭文件
fclose(pf);
pf = NULL;
}
int main()
{
char cfilename[] = "C:\\Users\\zhizhu\\Desktop\\hello\\文件拷贝.txt";
char vfilename[] = "C:\\Users\\zhizhu\\Desktop\\hello\\文件拷贝2.txt";
char* p = (char*)malloc(sizeof(char) * 1024);
int n = Cfile(p, cfilename);
Vfile(p, vfilename, n);
free(p);
p = NULL;
}