文件流传入其他函数后程序终止,文件单词统计功能异常
文件单词统计程序运行失败的问题排查与修复
核心问题分析
1. 未正确初始化并打开统计输出文件指针stats_file
代码仅声明了FILE *stats_file;,但未对其初始化或调用fopen打开目标文件。直接使用未初始化的指针调用fprintf会触发未定义行为,比如程序崩溃、写入垃圾数据。
2. 原文件指针file未重置位置
调用file_words_count(file)时,函数会读取整个文件直到末尾,此时文件指针停在文件结尾。后续调用words_array时,指针位置未重置,无法读取到文件内容,导致统计逻辑失效。
修复后的代码示例
#include <stdio.h> #include <stdlib.h> #include <string.h> // 实现正确的文件名读取函数 void input_text(char *filename, size_t size) { fgets(filename, size, stdin); // 移除fgets读取的换行符 char *newline = strchr(filename, '\n'); if (newline) *newline = '\0'; } void compute_stats(char words[30000][20], FILE *file) { int ch_counter = 0; int space_counter = 0; FILE *stats_file; char stats_filename[256]; // 定义数组存储输出文件名 printf("Enter the filename that you want to save the stats\n"); input_text(stats_filename, sizeof(stats_filename)); // 打开输出文件,检查是否成功 stats_file = fopen(stats_filename, "w"); if (!stats_file) { perror("Failed to open stats file"); exit(EXIT_FAILURE); } printf("This might take a while\nPlease wait\n"); int words_count = file_words_count(file); fprintf(stats_file, "words count = %d\n", words_count); // 重置原文件指针到开头,确保后续函数能重新读取内容 rewind(file); words_array(words, file, &ch_counter, &space_counter); int unique_words = different_words(words); fprintf(stats_file, "the number of different words is: %d\n", unique_words); different_word_lengths(words, stats_file); // 关闭文件释放资源 fclose(stats_file); printf("DONE!!!\n"); }
额外注意事项
- 所有文件操作后必须检查返回值,比如
fopen是否返回NULL,避免静默错误。 - 如果
file_words_count内部已处理指针重置,可省略rewind,但显式重置更可靠。 - 用
fgets而非gets读取文件名,防止缓冲区溢出。
内容的提问来源于stack exchange,提问作者Tasos Marinis
相关产品推荐
相关产品推荐

