C语言多文件循环读取:国家与首都数据存入数组问题求助
问题分析与修正方案
你的代码核心问题在于文件指针数组的初始化和遍历逻辑不符合C语言语法,同时存在数组越界的潜在风险,以下是具体修正:
主要错误点
- 错误的for循环写法:
for (FILE *country = {Africa, America, Asia, Europe, Oceania})不是C语言合法的循环结构,无法遍历多个文件指针。 - 提前初始化空指针数组:注释中的
FILE country[] = {Africa, America, Asia, Europe, Oceania};在文件指针未赋值时就初始化,会导致数组存储空指针。 - 未处理数组越界:
countryTable和capitalTable仅能存储15组数据,若文件中数据过多会导致内存溢出。
修正后的完整代码
#include <stdio.h> int main(){ FILE *Africa; FILE *America; FILE *Asia; FILE *Europe; FILE *Oceania; int countryIndex = 0; int capitalIndex; // 扩大数组容量避免越界,可根据实际文件数据调整 char countryTable[50][30]; char capitalTable[50][30]; // 定义文件指针数组,用于循环遍历 FILE *fileList[] = {Africa, America, Asia, Europe, Oceania}; const int fileCount = sizeof(fileList) / sizeof(fileList[0]); // 逐个打开文件并赋值到数组 fileList[0] = fopen("Africa.txt", "r"); fileList[1] = fopen("America.txt", "r"); fileList[2] = fopen("Asia.txt", "r"); fileList[3] = fopen("Europe.txt", "r"); fileList[4] = fopen("Oceania.txt", "r"); // 检查所有文件是否打开成功,失败则关闭已打开文件再退出 for(int i = 0; i < fileCount; i++){ if(fileList[i] == NULL){ printf("Error, failed when trying to open file at index %d.\n", i); for(int j = 0; j < i; j++){ fclose(fileList[j]); } return 1; } } // 遍历每个文件指针,读取国家和首都数据 for(int i = 0; i < fileCount; i++){ FILE *currentFile = fileList[i]; // 读取时检查数组是否已满,且确保一次读取到一组有效数据 while(countryIndex < sizeof(countryTable)/sizeof(countryTable[0]) && fscanf(currentFile, "%s %s", countryTable[countryIndex], capitalTable[countryIndex]) == 2){ countryIndex++; } } // 输出所有读取到的国家和首都信息 for (capitalIndex = 0; capitalIndex < countryIndex; capitalIndex++){ printf("Country : %s - Capital : %s\n", countryTable[capitalIndex], capitalTable[capitalIndex]); } // 统一关闭所有文件 for(int i = 0; i < fileCount; i++){ fclose(fileList[i]); } return 0; }
关键修正说明
- 文件指针数组的正确使用:先定义
FILE *fileList[]数组,在文件打开成功后将指针存入数组,通过下标遍历数组实现循环处理多个文件。 - 优化资源管理:文件打开失败时关闭已打开的文件,避免资源泄漏;统一关闭所有文件,提升代码健壮性。
- 避免数组越界:读取数据时增加数组容量判断,同时合并
fscanf调用,通过返回值确认是否读取到一组完整的国家和首都数据。 - 统一输出逻辑:将输出放在所有文件读取完成后,避免重复输出中间结果(若需每个文件读完即输出,可将输出代码移至对应文件的读取循环后)。
内容的提问来源于stack exchange,提问作者Jean-Lou Gilbertas
相关产品推荐
相关产品推荐

