c - 在 C 中复制二进制文件的神秘问题

标签 c file-io binaryfiles argv

嘿社区,我在从命令行复制二进制文件时遇到问题,看看我的尝试。下面的代码复制了 srcFile 上的第一个字符并以某种方式停止,你们能帮我弄清楚解决这个问题的方法以及它发生的原因吗?

#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;
}

输入源文件: 10100101

目标文件的预期输出: 10100101

目标文件输出: 1

最佳答案

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

看看>在哪里...在分配给currBit之前与零进行比较,因此您总是分配一个 bool 值值(1/0)。将 > 移动到括号的最外层。

关于c - 在 C 中复制二进制文件的神秘问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37087430/

相关文章:

perl - 有没有办法在 perl 中本地更改输入记录分隔符?

c - 如何在 c 中制作二进制文件 ---- struct within a struct

c - 如何检查字符串是否在二进制文件中

c - 从 zip 文件动态加载(dlopen)共享库(.so 文件)

stdint 的 int8_t 可以存在于没有 8 位字节的架构上吗?

python - 如何让python打开外部文件?

c++ - 在 C(或 C++)中循环遍历 WAV 文件

python - 使用 distutils 将 C 代码集成到 Python 库中的最常规方法是什么?

c - 实时时钟,MSP430

c++ - 如何调整/加长/截断文件并在开头留出更多空间?