Compare two files

前端 未结 6 1651
一向
一向 2020-12-14 03:57

I\'m trying to write a function which compares the content of two files.

I want it to return 1 if files are the same, and 0 if different.

ch1 an

6条回答
  •  误落风尘
    2020-12-14 04:28

    Since you've allocated your arrays on the stack, they are filled with random values ... they aren't zeroed out.

    Secondly, strcmp will only compare to the first NULL value, which, if it's a binary file, won't necessarily be at the end of the file. Therefore you should really be using memcmp on your buffers. But again, this will give unpredictable results because of the fact that your buffers were allocated on the stack, so even if you compare to files that are the same, the end of the buffers past the EOF may not be the same, so memcmp will still report false results (i.e., it will most likely report that the files are not the same when they are because of the random values at the end of the buffers past each respective file's EOF).

    To get around this issue, you should really first measure the length of the file by first iterating through the file and seeing how long the file is in bytes, and then using malloc or calloc to allocate the buffers you're going to compare, and re-fill those buffers with the actual file's contents. Then you should be able to make a valid comparison of the binary contents of each file. You'll also be able to work with files larger than 64K at that point since you're dynamically allocating the buffers at run-time.

提交回复
热议问题