-3

Hey community i'm having trouble in replicating binary files from the command line have a look at my try. The code under copies the first character on the srcFile and stops somehow, can you guys help me figure the way i can fix this and the reason it happens?

#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 8500
int main(int argc, char** argv)
{
char buffer[BUFSIZE];
size_t currBit;


FILE *srcFile = fopen(argv[1], "r+b");

if (!srcFile)
{
    printf("source file doesnt exist or problem with allocating the memory");
    return 1;
}
FILE *dstFile = fopen(argv[2], "r+b");
if (dstFile)
{
    printf("Destination file already exists\nfor overwriting enter 1 \nfor exit enter 2\n");
    _flushall();
    switch (getchar())
    {
    case '1':
        fclose(dstFile);
        dstFile = fopen(argv[2], "w+b");
        if (!dstFile)
        {
            printf("Problem with allocating the memory");
        }
        while ((currBit = fread(buffer, sizeof(char),BUFSIZE, srcFile) > 0))
        {
            fwrite(buffer, sizeof(char), currBit, dstFile);
        }

        break;
    case '2':
        system("pause");
        return 0;
        break;
    default:
        printf("next time you should enter numbers as following");
    }
}
else
{
    dstFile = fopen(argv[2], "w+b");
    while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))
    {
        fwrite(buffer, sizeof(char), currBit, dstFile);
    }
    if (!dstFile)
    {
        printf("Problem with allocating the memory");
    }
}


fclose(srcFile);
fclose(dstFile);

getchar();
return 0;
}

Input Source file: 10100101

Expected Output From Destination File: 10100101

Destination File Output: 1

  • 1
    Voting to close as why isn't my code working. Use printf + gdb to minimize. – Ciro Santilli OurBigBook.com May 07 '16 at 10:40
  • 2
    'while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))' why do developers continually write complex, compound expressions? Stop writing 'clever' code. In software development, 'clever' means 'buggy and difficult to debug'. – Martin James May 07 '16 at 10:41
  • 2
    Also as @CiroSantilli巴拿馬文件六四事件法轮功 says, use your debugger before posting to SO:( – Martin James May 07 '16 at 10:44

2 Answers2

1
while ((currBit = fread(buffer, sizeof(char),BUFSIZE, srcFile) > 0))

Look at where the > is... You are comparing with zero before assigning to currBit, so you are always assigning a boolean value (1/0). Move > to the outermost layer of parentheses.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
-1
'while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))'

Misplaced brackets in the compound expression result in 'currBit' being loaded with a boolean result.

Martin James
  • 24,453
  • 3
  • 36
  • 60