I've been trying to copy 2 binary files one to the other using fread
and write
. I've read a couple of articles that explain how they work but I don't understand what is my mistake here.
I've tried switching the char fread
is used on to an int
so the -1
wont interfere with the process but it didn't seem to work.
Some links I looked up to search for an answer:
Why is “while (!feof(file))” always wrong?
https://www.tutorialspoint.com/c_standard_library/c_function_fwrite.htm
https://www.tutorialspoint.com/c_standard_library/c_function_fread.htm
Copying Binary Files
Copying data from one text file to another in C
while (tempNum != EOF) {
fread(tempNum, 1, 1, fptr);
fwrite(tempNum, 1, 1, fp);
}
Example for you to test:
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
FILE *fptr;
FILE *fp;
int main(int argc, char** argv)
{
int flag = 0;
int exist = 0;
char currentChar = 0;
int tempNum = 0;
fptr = 0;
fp = fopen(*(argv + 3), "r");
fptr = fopen(*(argv + 2), "r");
char temp_array[10000] = { 0 };
if (fptr == NULL)
{
printf("we cannot extract from nothing.");
flag++;
}
else if (fp != NULL)
{
printf("This file already exists. If you would like to overwrite it enter 0. %s");
scanf("%d", &flag);
}
if (!strcmp(*(argv + 1), "textCopy") && flag == 0)
{
fclose(fp);
fclose(fptr);
printf("A");
fp = fopen(*(argv + 3), "w");
fptr = fopen(*(argv + 2), "r");
printf("%s , %s", *(argv + 2), *(argv + 3));
while (currentChar != EOF)
{
printf("a");
currentChar = fgetc(fptr);
fputc(currentChar, fp);
}
fclose(fp);
fclose(fptr);
}
else if (!strcmp(*(argv + 1), "binaryCopy") && flag == 0)
{
printf("A");
fptr = fopen(*(argv + 2), "r");
fp = fopen(*(argv + 3), "w");
while (tempNum != EOF)
{
fread(tempNum, 1, 1, fptr);
fwrite(tempNum, 1, 1, fp);
}
}
getchar();
getchar();
return 0;
}
Expected: to get 2 identical files.
Actual: I successfully copy the first 6 bytes of the file (I used hex workshop) but afterwards Visual Studio crashed and said that the parameters passed to the function fread
consider the input fatal.