在C语言中复制二进制文件的神秘问题
嘿,社区,我在从命令行复制二进制文件时遇到了麻烦,看看我的尝试。下面的代码复制了src文件中的第一个字符,然后不知怎么停了下来,你们能帮我找出解决这个问题的方法和原因吗在C语言中复制二进制文件的神秘问题,c,file-io,binaryfiles,argv,C,File Io,Binaryfiles,Argv,嘿,社区,我在从命令行复制二进制文件时遇到了麻烦,看看我的尝试。下面的代码复制了src文件中的第一个字符,然后不知怎么停了下来,你们能帮我找出解决这个问题的方法和原因吗 #include <stdio.h> #include <stdlib.h> #define BUFSIZE 8500 int main(int argc, char** argv) { char buffer[BUFSIZE]; size_t currBit; FILE *srcFile = fop
#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;
}
#包括
#包括
#定义BUFSIZE 8500
int main(int argc,字符**argv)
{
字符缓冲区[BUFSIZE];
大小\u t当前位;
FILE*srcFile=fopen(argv[1],“r+b”);
如果(!srcFile)
{
printf(“源文件不存在或内存分配有问题”);
返回1;
}
FILE*dstFile=fopen(argv[2],“r+b”);
如果(DST文件)
{
printf(“目标文件已存在,\n用于覆盖输入1\n用于退出输入2\n”);
_flushall();
开关(getchar())
{
案例“1”:
fclose(dstFile);
dstFile=fopen(argv[2],“w+b”);
如果(!dstFile)
{
printf(“内存分配问题”);
}
而((currBit=fread(buffer,sizeof(char),BUFSIZE,srcFile)>0))
{
fwrite(缓冲区、sizeof(char)、currBit、dstFile);
}
打破
案例“2”:
系统(“暂停”);
返回0;
打破
违约:
printf(“下次您应按以下方式输入数字”);
}
}
其他的
{
dstFile=fopen(argv[2],“w+b”);
而((currBit=fread(buffer,sizeof(char),BUFSIZE,srcFile)>0))
{
fwrite(缓冲区、sizeof(char)、currBit、dstFile);
}
如果(!dstFile)
{
printf(“内存分配问题”);
}
}
fclose(src文件);
fclose(dstFile);
getchar();
返回0;
}
输入源文件:
10100101
目标文件的预期输出:
10100101
目标文件输出:
一,
看看
在哪里。。。在分配给currBit
之前,您将与零进行比较,因此始终分配布尔值(1/0)。将>
移动到括号的最外层
'while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))'
复合表达式中括号放错会导致“currBit”加载布尔结果。投票关闭,因为我的代码为什么不能工作。使用printf+gdb最小化“while((currBit=fread(buffer,sizeof(char),BUFSIZE,srcFile)>0))”为什么开发人员不断编写复杂的复合表达式?停止编写“聪明”的代码。在软件开发中,“聪明”的意思是“有缺陷且难以调试”巴拿馬文件六四事件法轮功 说明,在发布到SO之前使用调试器:(
'while ((currBit = fread(buffer, sizeof(char), BUFSIZE, srcFile) > 0))'