I'm getting strange results. When I use fread() to store my file in my buffer, running a sizeof() on it produces a value of 4. Also, correct me if I'm wrong, but I think the correct sequence of events is:
- open file (read/binary mode)
- get length of file
- allocate buffer memory
- copy file into buffer
- open output file (write/binary mode)
- write buffer to output file
I've done this, so I just don't see what I'm doing wrong here. Again, no compilation errors, and I'm not getting caught in any self-coded error checks. Here is the current code:
Code:
void Copy_file() {
char filename[1024];
char *buffer;
long lSize;
size_t result;
FILE * file_src;
FILE * file_dst;
/* Get path */
GetModuleFileName(NULL,filename,1024);
file_src = fopen(filename,"rb");
if (file_src == NULL) {
fprintf(stderr,"Cannot open source file %s.\n",filename);
return;
}
/* Get file size */
fseek(file_src,0,SEEK_END);
lSize = ftell(file_src);
rewind(file_src);
printf("lSize: %d\n",lSize); // prints 28792
/* Allocate memory to contain file*/
buffer = (char*) malloc (sizeof(char) *lSize);
if (buffer == NULL) {
fprintf(stderr, "Memory allocation error.\n");
fclose(file_src);
return;
}
/* Copy file into buffer */
result = fread(buffer, 1, lSize, file_src);
if (result != lSize) {
("Reading error.\n",stderr);
return;
}
printf("sizeof(result) == %d\n",sizeof(result)); // prints 4
/* Open output file */
file_dst = fopen("C:\\test.exe","wb");
if (!file_dst) {
printf("Cannot copy destination file.\n");
fclose(file_src);
return;
}
/* Write output file */
fwrite(buffer, 1, sizeof(buffer), file_dst);
printf("sizeof(buffer) == %d\n",sizeof(buffer)); // prints 4
free(buffer);
fclose(file_src);
fclose(file_dst);
printf("File copy complete.\n");
return;
}