C语言fscanf读取文件整数存入数组结果全为0问题求助
问题说明
调用自定义fileReading()函数从test.txt文件逐行读取整数存入对应数组时,程序运行无报错,但最终数组存储的数值全部为0,和文件内实际数值不符。
复现信息
- 待读取
test.txt文件内容:
1 2 3 4 5 6
- 程序实际运行输出:
No of Rows : 2 The Contents of File are given below : 0 0 0 0 0 0
- 原功能实现代码:
#include<sdtio.h> #include<string.h> #include<stdlib.h> int runningProcess[10]; int lockedProcess[10]; int waitingProcess[10]; int numOfRows=1; void fileReading(){ FILE* fptr; fptr = fopen("test.txt","r"); char c; for (c = getc(fptr); c != EOF; c = getc(fptr)){ // 统计换行符数量计算行数 if (c == '\n'){ numOfRows = numOfRows + 1; } } printf("No of Rows : %d\n",numOfRows); for(int i=0; i<numOfRows;i++){ fscanf(fptr, "%d* %d* %d*", &runningProcess[i], &lockedProcess[i], &waitingProcess[i]); } printf("The Contents of File are given below :\n"); for (int i = 0; i < numOfRows; i++) { printf("%d %d %d\n", runningProcess[i],lockedProcess[i],waitingProcess[i]); } fclose(fptr); }
问题根因
一共三个核心问题导致读取失败:
- 文件指针位置未重置:第一个循环逐字符统计行数时,文件指针
fptr会随着读取操作向后移动,统计完行数后指针已经指向文件末尾(EOF位置),后续直接调用fscanf读取时没有任何内容可读,不会给数组元素赋值。而全局数组默认初始值为0,因此最终输出全0。 fscanf格式字符串写法错误:格式串中写的%d*属于错误写法,*如果作为格式控制符需要紧跟在%后(表示赋值抑制),写在d后代表需要匹配文本中字面的*字符,但测试文件中不存在该字符,即使文件指针位置正确也会匹配失败,无法读取数值。- 存在语法笔误和鲁棒性缺陷:头文件
sdtio.h为拼写错误,正确写法是stdio.h;存储getc返回值的变量c定义为char类型存在风险,EOF值为-1,若编译器默认char为无符号类型,将永远无法匹配到EOF,会导致统计行数的循环死循环;另外fopen后未做空指针判断,文件不存在时会直接触发内存访问错误。
修复方案
- 统计完行数后,调用
rewind(fptr)将文件指针重置到文件起始位置; - 将
fscanf的格式串修正为"%d %d %d",移除多余的错误*字符; - 修正头文件拼写,将存储读取字符的变量改为
int类型,增加文件打开成功的判断逻辑。
修复后的完整代码:
#include<stdio.h> #include<string.h> #include<stdlib.h> int runningProcess[10]; int lockedProcess[10]; int waitingProcess[10]; int numOfRows=1; void fileReading(){ FILE* fptr; fptr = fopen("test.txt","r"); // 增加文件打开判断 if (fptr == NULL) { printf("打开文件失败\n"); return; } int c; for (c = getc(fptr); c != EOF; c = getc(fptr)){ if (c == '\n'){ numOfRows = numOfRows + 1; } } printf("No of Rows : %d\n",numOfRows); // 重置文件指针到开头 rewind(fptr); for(int i=0; i<numOfRows;i++){ // 修正格式串 fscanf(fptr, "%d %d %d", &runningProcess[i], &lockedProcess[i], &waitingProcess[i]); } printf("The Contents of File are given below :\n"); for (int i = 0; i < numOfRows; i++) { printf("%d %d %d\n", runningProcess[i],lockedProcess[i],waitingProcess[i]); } fclose(fptr); }
内容的提问来源于stack exchange,提问作者Crissomolo
相关产品推荐
相关产品推荐

