C语言while循环未按预期工作:文件仅复制单个字符问题求助
C语言文件复制程序仅复制单个字符的修复方案
你贴出的代码逻辑本身是正确的,但实际运行只复制单个字符,大概率是代码中的换行符语法错误导致编译失败,你实际运行的可能是未完成的旧版本代码(比如最初用fgetc单字符读写的版本)。
问题根源
代码中所有printf语句里的换行都写成了直接换行( ),这不符合C语言语法——C语言中必须用\n表示换行符,这种语法错误会导致编译报错,你可能没有修复编译错误就强行运行了旧版代码。
修复后的完整代码
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { // 检查参数数量是否正确 if (argc != 3) { printf("Usage: %s [source_file] [destination_file]\n", argv[0]); return 1; } // 打开源文件(二进制读模式) FILE *source = fopen(argv[1], "rb"); if (source == NULL) { printf("Error: Unable to open the source file.\n"); return 1; } // 打开目标文件(二进制写模式) FILE *destination = fopen(argv[2], "wb"); if (destination == NULL) { printf("Error: Unable to open the destination file.\n"); fclose(source); return 1; } char buffer[1024]; size_t bytes_read; // 批量读写复制文件 while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) { fwrite(buffer, 1, bytes_read, destination); } // 关闭文件 fclose(source); fclose(destination); printf("File copied successfully.\n"); return 0; }
验证步骤
- 将代码中的所有换行替换为
\n,确保编译无错误 - 使用
gcc -o filecopy filecopy.c编译代码(替换为你的文件名) - 运行程序时传入正确参数:
./filecopy 源文件路径 目标文件路径
这段代码以1024字节为缓冲区批量读写,能正确复制任意大小的文本或二进制文件,不会出现仅复制单个字符的问题。
内容的提问来源于stack exchange,提问作者dthnick
相关产品推荐
相关产品推荐

