Tomer Shamir
Tomer Shamir

Reputation: 11

how to use fread on malloc strings

Can someone help me understand why it's entering unknown chars to temp? I'm trying to binary copy one file to the other one. Thanks a head!

 int size=0;
 fseek(srcFiles,0, SEEK_END);
 size = ftell(srcFiles);
 printf("%d", size);
 char* temp = (char*)malloc(sizeof(char)*(size+1));
 fread(temp, sizeof(char), size , srcFiles);
 printf("%s", temp);
 fwrite(temp, sizeof(char), size , dstFiles)

Upvotes: 1

Views: 1368

Answers (1)

Florian Weimer
Florian Weimer

Reputation: 33717

It seems the problem is that you do not seek back to the start of the file after seeking to the end (to determine the file size using ftell).

As already has been said, you also need to add a null terminator if you use printf in this way.

Upvotes: 1

Related Questions