So I started out just by trying to copy a file that is on my own system. The code works, it can copy an image but my problem when I want to use some block reading function like fread or fwrite. Why wont the image copy? When I use fread/write the file isn't the same size as the original. My method of writing on a character by character basis may be slow, but it works. So can someone tell me why the commented code wont work for an image? It does for text files but not images.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void error(char *err){
printf("%s\n",err);
exit(-1);
}
char *get_copy(char* filename){
int i = 0;
char *file = malloc(strlen(filename) + strlen("_copy.ext"));
while(*filename != '.') file[i++] = *filename++;
strcat(file,"_copy");
strcat(file,filename);
return file;
}
int main(int argc, char *argv[]){
if(argc != 2){
char err_msg[32];
snprintf(err_msg,sizeof(err_msg),"Usage: %s <file_to_copy>",argv[0]);
error(err_msg);
}
FILE *ifile, *ofile;
char *out_file, c;
int file_size = 0, nread = 0;
if(!(ifile = fopen(argv[1], "r")))
error("Error opening read file");
out_file = get_copy(argv[1]);
fseek(ifile,0,SEEK_END);
file_size = ftell(ifile);
fseek(ifile,0,SEEK_SET);
if(!(ofile = fopen(out_file,"w")))
error("Error opening write file");
printf("Writing %d bytes to %s\n", file_size ,out_file);
while(nread < file_size){
c = fgetc(ifile);
fputc(c,ofile);
nread++;
}
printf("%d bytes written to %s\n",nread, out_file);
fclose(ifile);
fclose(ofile);
return 0;
}