int main(void) { FILE * src=fopen("src.bin","rb"); FILE * des=fopen("des.bin","wb"); char buf[20]; int readcnt;
if(src==NULL || des==NULL)
{
puts ("File Open Failed!");
return -1;
}
while(1)
{
readcnt=fread((void*)buf,1,sizeof(buf),src);
if(readcnt<sizeof(buf))
{
if(feof(src)!=0)
{
fwrite((void)*buf,1,readcnt,des);
"Copy file completed!");
break;
}
else
puts ("File copy failed!");
break;
}
fwrite((void)*buf,1,sizeof(buf),des);
}
fclose(src);
fclose(des);
return 0;
}
After making a file copy within the while function, when you reach the EOF, the reason why you insert fwrite((void)*buf,1,readcnt,des) is because it is not copied as much as the size of the buf, but I don't understand it at all. Can you explain it?
fwrite fread
The purpose of the source code is to copy a certain size from src.bin and store it in des.bin sequentially to create one more identical file.
It's literally copying.
Suppose that src.bin is 110.
And since you need to copy it by a certain size, create a space of char buf[20];
20.
while(1) // Repeat until you meet break
{
readcnt=fread((void*)buf,1,sizeof(buf),src);
readcnt=fread((void*)buf,1,sizeof(buf),src);
to cut from the front by the size of the buff and store it in the buff. And readcnt is the actual size read in src.bin.
Write what is stored in the buf to the actual des.bin via fwrite((void)*buf,1,sizeof(buf,des);
.
So, since src.bin is 110 in size, we're going to write it up to 100 in 5 iterations, and readcnt is 10 in the 6th iteration. 20, 40, 60, 80, 100. And in the sixth, the src.bin size is 110, so you'll only read the last 10. (Stream is better to understand if you study it separately.)
if(readcnt<sizeof(buf))
{
if(feof(src)!=0)
{
fwrite((void)*buf,1,readcnt,des);
"Copy file completed!");
break;
}
Now I don't understand it, but it's simple if you understand the explanation above.
If readcnt is less than the buf size of 20, that is, if it is the last iteration, it is done.
Save the last 10 size buf and escape while break.
Clean up resources and exit the program.
© 2024 OneMinuteCode. All rights reserved.