I made simple program that can copy source file and paste another defined file.
Below is my code.
int main(void) {
FILE *fp_src;
FILE *fp_dest;
char src[100];
char dest[100];
fputs("source file : ", stdout);
gets_s(src);
fp_src = fopen(src, "rb");
fputs("dest file : ", stdout);
gets_s(dest);
fp_dest = fopen(dest, "wb");
char ch;
//int ch;
while ((ch = fgetc(fp_src)) != EOF) {
fputc(ch, fp_dest);
}
fclose(fp_src);
fclose(fp_dest);
return 0;
}
When I use fgetc function, it returns integer-type value because the EOF needs 4-bytes space. I know this concept, but, when I was making this program, I used the character-type for storing the returning value by mistake. And then, I ran this program, the destination file (the file that I want to copy) cannot properly create. (the file size is 0-byte) Therefore I changed the character-type into integer-type and then I found it was working fine.
As I mentioned above, I know that fgetc returns the integer-type value. However, I don't think that using character-type for fgetc wouldn't be a problem but it was a critical problem when copying file with fgetc function.
So I didn't get it why this situation happened.
Could you help me understand it more detailed?
gets_s()needs a length argument too. Did the code compile without warnings? If so, you need to turn up the warning levels on your compiler — or get a better compiler.gets_s()work; you don't verify that the calls tofopen()work. You don't know that the code should be working. And you need to use at minimumshort, and may as well useintlike everyone else does, to capture the return value fromfgetc(). Anything else is error prone at best.