C语言文本读取分析程序故障排查求助
问题排查与修正建议
以下是针对你的C语言关键词统计程序的常见问题排查点及修正方向:
文件读取有效性校验
必须在调用fopen后立即检查文件指针是否为NULL,避免后续操作因文件未打开而崩溃。示例代码:#include <stdio.h> #include <stdlib.h> int main() { char main_file[256], keyword_file[256]; printf("Enter main text file name: "); scanf("%s", main_file); FILE *main_fp = fopen(main_file, "r"); if (main_fp == NULL) { perror("Failed to open main text file"); exit(EXIT_FAILURE); } // 关键词文件同理 printf("Enter keyword file name: "); scanf("%s", keyword_file); FILE *key_fp = fopen(keyword_file, "r"); if (key_fp == NULL) { perror("Failed to open keyword file"); fclose(main_fp); exit(EXIT_FAILURE); } // 后续逻辑 }exclude.h 标点过滤逻辑
确保exclude.h中定义的排除字符集合完整,且过滤逻辑正确。可编写辅助函数判断字符是否需要排除,处理主文本时将标点替换为空格或截断,保证单词正确分割:#include "exclude.h" // 假设exclude.h中定义了char exclude_chars[] = ".,!?;:'\"()[]{}..."; int is_excluded(char c) { for (int i = 0; exclude_chars[i] != '\0'; i++) { if (c == exclude_chars[i]) { return 1; } } return 0; } // 处理单词中的标点:截断标点后的部分 void process_word(char *word) { for (int i = 0; word[i] != '\0'; i++) { if (is_excluded(word[i])) { word[i] = '\0'; break; } } }区分大小写的关键词匹配
使用strcmp而非strcasecmp进行精确匹配,保证大小写敏感。读取主文本时,按空白字符分割单词,逐个与关键词数组中的元素比对,匹配成功则对应计数加1:typedef struct { char word[256]; int count; } KeywordStat; // 假设已从关键词文件读取所有关键词到KeywordStat数组stats中,长度为key_count char buffer[256]; while (fscanf(main_fp, "%s", buffer) != EOF) { process_word(buffer); for (int i = 0; i < key_count; i++) { if (strcmp(buffer, stats[i].word) == 0) { stats[i].count++; break; } } }按频率降序排序
使用qsort实现高效排序,自定义比较函数实现降序逻辑:int compare_stats(const void *a, const void *b) { KeywordStat *stat_a = (KeywordStat *)a; KeywordStat *stat_b = (KeywordStat *)b; // 降序:后者计数减前者计数 return stat_b->count - stat_a->count; } // 排序调用 qsort(stats, key_count, sizeof(KeywordStat), compare_stats); // 输出结果 for (int i = 0; i < key_count; i++) { printf("%s: %d\n", stats[i].word, stats[i].count); }边界与内存问题
- 确保关键词数组和单词缓冲区的大小足够容纳最长的关键词/单词,避免数组越界;
- 若关键词数量不确定,建议使用动态内存分配(
malloc+realloc)扩展数组; - 所有打开的文件必须在程序结束前调用
fclose关闭。
内容的提问来源于stack exchange,提问作者kristian williams
相关产品推荐
相关产品推荐

