如何用C语言读取未知大小文件并将单词存入动态分配二维数组
动态读取文件单词存储到二维字符数组实现方案
以下是修复后可直接运行的完整代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> // 函数前置声明 int fileConverter(char *filename); int main(void) { char filename[256]; // 扩大文件名缓冲区避免溢出 printf("Input the filename: "); scanf("%255s", filename); // 限制输入长度避免溢出 int wordCnt = fileConverter(filename); return 0; } int fileConverter(char *filename) { FILE *file = fopen(filename, "r"); if(file == NULL) { perror("Failed to open file"); exit(EXIT_FAILURE); } // 动态数组初始配置 int arrCapacity = 16; // 初始数组容量 int wordCnt = 0; // 已存储的单词数 char **words = (char**)malloc(arrCapacity * sizeof(char*)); if(words == NULL) { perror("Failed to allocate memory for word array"); fclose(file); exit(EXIT_FAILURE); } char buf[256]; // 临时缓冲区存储单个单词,默认适配最长255字节的单词 // 用fscanf读单词,自动跳过空格、换行、制表符等空白分隔符 while(fscanf(file, "%255s", buf) == 1) { // 数组容量不足时自动扩容为原来的2倍 if(wordCnt >= arrCapacity) { arrCapacity *= 2; char **temp = (char**)realloc(words, arrCapacity * sizeof(char*)); if(temp == NULL) { perror("Failed to expand word array"); // 释放已分配内存避免泄漏 for(int i = 0; i < wordCnt; i++) free(words[i]); free(words); fclose(file); exit(EXIT_FAILURE); } words = temp; } // 为当前单词分配内存并拷贝内容 words[wordCnt] = (char*)malloc((strlen(buf) + 1) * sizeof(char)); if(words[wordCnt] == NULL) { perror("Failed to allocate memory for single word"); for(int i = 0; i < wordCnt; i++) free(words[i]); free(words); fclose(file); exit(EXIT_FAILURE); } strcpy(words[wordCnt], buf); wordCnt++; } fclose(file); // 打印所有读取到的单词 for(int i = 0; i < wordCnt; i++) { printf("a[%d] = %s\n", i, words[i]); } printf("The file contains %d words.\n", wordCnt); // 不需要继续使用words时释放内存 for(int i = 0; i < wordCnt; i++) { free(words[i]); } free(words); return wordCnt; }
核心修改说明
- 补充了函数前置声明,避免main函数调用时编译报错
- 修复原代码变量未定义、arr和words变量混用的基础语法问题
- 采用边读边扩容的逻辑适配未知大小的文件,初始容量设为16,容量不足时自动扩容为原来的2倍,兼顾内存占用和扩容效率
- 用
fscanf("%s")替代fgets读取单词,自动跳过空白分隔符,符合读取单词的需求 - 所有内存分配操作都做了错误判断,避免空指针访问,异常场景下先释放已分配内存再退出,避免内存泄漏
- 限制文件名、单词的读取长度,避免缓冲区溢出风险
- 修复原代码中把字符串指针
"\0"赋值给字符变量的语法错误
内容的提问来源于stack exchange,提问作者PaYeeTeX
相关产品推荐
相关产品推荐

