Reputation: 150
I'm writing a wrapper to help me in my future projects (I finished C book), and want to copy a file without using fgetc
. Here's my code, it doesn't work:
int CopyFile(char* filename, char* dest)
{
FILE* fp, *fout;
fp = fopen(filename,"rb");
//fout = fopen(dest, "wb");
if(fp == NULL)
{
return -1;
}
/*while((c = fgetc(fp)) != EOF)
{
fputc(c,fout);
}*/
long size = GetFileSize(fp);
printf("%lu", size);
char* file = malloc(size);
fread(file, size, 1, fp);
//fclose(fp);
fout = fopen(dest, "wb");
fwrite(file, size, 1, fout);
fclose(fp);
fclose(fout);
return 0;
}
I even open the files with a hexeditor and they aren't similar. What am I doing wrong?
Upvotes: 0
Views: 243
Reputation: 409176
The problem is in the GetFileSize
function, where you move the file-pointer to the end, but you never rewind to the beginning again.
That means your fread
function call will not actually read anything, as the pointer already is at the end of the file. So what's written is the contents of the allocated memory, which is indeterminate (and will be seemingly random).
If you checked what fread
returned, you would have seen this immediately.
Let this be a lesson on always checking the return values of functions which can fail in one way or the other.
Upvotes: 3