C语言带校验的文件解码程序输出单词不完整问题求助
问题根因
- 核心错误:4位数据nibble提取逻辑错误
代码中nibble = (byte >> 3) & 0x07;使用的掩码0x07仅能保留低3位数据,直接丢弃了数据最高位d3。你测试的单词ferret所有字符对应的数据最高位恰好为0,因此未触发错误;而guitar中字符i对应的数据最高位为1,被丢弃后值发生变化,最终输出为a,完全符合你给出的错误表现。 - 次要风险点:fgetc返回值存储类型错误
fgetc返回值为int类型,包含0~255的合法字符值和EOF(值为-1),你用uint8_t类型存储返回值会导致字符0xFF被误判为EOF,提前终止文件读取。 - 优化点:feof的使用逻辑存在多读一次无效字符的可能,建议调整循环判断逻辑。
修复方案
- 修正nibble提取的掩码,将
0x07替换为0x0F,保留完整4位数据位 - 将存储fgetc返回值的变量类型改为int,避免EOF误判
- 调整循环逻辑为读操作在前,判断是否为EOF在后,避免多读无效字符
- 可选:将错误位修正的多个if判断改为switch分支,提升执行效率,同时添加默认分支处理无错误场景
修复后完整代码
#include <stdio.h> #include <stdint.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *inputFile, *outputFile; int charFile; // 修改为int类型存储fgetc返回值 uint8_t highNibble; int i = 1; uint8_t byte; uint8_t d0, d1, d2, d3; uint8_t p0, p1, p2; uint8_t finalByteParity = 0; uint8_t nibble; // 修改为uint8_t类型更匹配数据范围 if (argc == 3) { printf("程序名称:%s\n", argv[0]); printf("输入文件路径:%s\n", argv[1]); printf("输出文件路径:%s\n", argv[2]); inputFile = fopen(argv[1], "rb"); // 改用二进制模式避免跨平台换行符转换破坏原始数据 outputFile = fopen(argv[2], "wb"); // 改用二进制模式避免跨平台换行符转换破坏原始数据 if (inputFile == NULL) { printf("打开输入文件%s失败\n", argv[1]); } else if (outputFile == NULL) { printf("打开输出文件%s失败\n", argv[2]); } else { // 调整循环逻辑,先读再判断,避免多读无效字符 while ((charFile = fgetc(inputFile)) != EOF) { byte = (uint8_t)charFile; // 修正掩码为0x0F,保留4位完整数据 nibble = (byte >> 3) & 0x0F; d0 = (nibble >> 0) & 0b0001; d1 = (nibble >> 1) & 0b0001; d2 = (nibble >> 2) & 0b0001; d3 = (nibble >> 3) & 0b0001; p0 = (d0 + d1 + d2) % 2; p1 = (d0 + d1 + d3) % 2; p2 = (d1 + d2 + d3) % 2; finalByteParity = p0 << 0; finalByteParity |= p1 << 1; finalByteParity |= p2 << 2; uint8_t checkByteParity = byte & 0x07; uint8_t checkFinalParity = finalByteParity & 0x07; int fullCheck = checkByteParity ^ checkFinalParity; switch(fullCheck) { case 7: nibble ^= 0x02; break; case 3: nibble ^= 0x01; break; case 5: nibble ^= 0x04; break; case 6: nibble ^= 0x08; break; default: break; // 无错误或者多位错误不处理 } if (i % 2 == 0) { uint8_t restoredByte = highNibble << 4 | nibble; fputc(restoredByte, outputFile); } else { highNibble = nibble; } i++; } } fclose(inputFile); fclose(outputFile); } else { printf("参数错误,请输入:程序名 输入文件路径 输出文件路径\n"); } return 0; }
内容的提问来源于stack exchange,提问作者Tamaki.-San
相关产品推荐
相关产品推荐

