使用fscanf读取文件宽高时出现异常值问题求助
文件读取宽高时的乱码/无输出问题分析与修复
我需要从文件首两行读取整数作为地图的宽度和高度,但运行代码后宽度输出乱码值,高度无有效输出。相关代码、文件示例及当前输出如下:
原代码
#include <stdio.h> #include <stdlib.h> #define EMPTY '-' #define HUMAN 'H' #define ZOMBIE 'Z' // Function Prototypes char** read_map_from_txt(const char* filename, int *width, int *height); int main(int argc, char **argv) { int width, height; char *filename[50] = argv[0]; char **grid = read_map_from_txt(filename, &width, &height); return 0; } char** read_map_from_txt(const char* filenamee, int *width, int *height) { // This function should read width and height from the given filename and assign these values to the pointers given. // It also should allocate the memory for the grid and return a pointer for grid. // Write your code below // char filename[30] = "maps/map_1.txt"; FILE *file = fopen(filename, "r"); char line[100]; *width = fscanf(file, "%d", width); printf("w - %d\n", width); *height = fscanf(file, "%d", height); printf("h - %s\n", height); while(fgets(line, sizeof(line), file) != NULL) { printf("%s", line); } fclose(file); return NULL; }
文件内容示例
3
3
....(其他信息)
当前输出
w - -437801428
h --H---
-ZH--
错误原因分析
fscanf使用逻辑错误:fscanf的返回值是成功读取的输入项数,不是读取到的数值。你错误地将返回值赋值给*width,同时直接传递指针变量width给fscanf的第二个参数(这里虽类型匹配,但赋值逻辑完全错误),导致*width存储的是读取成功标记而非目标整数,打印时又直接输出指针地址,因此出现乱码。height的处理同理。printf格式符不匹配:打印width时用%d输出指针变量本身(内存地址)而非指针指向的数值*width;打印height时错误使用%s(字符串格式符)输出整数指针,导致无有效输出。- 缺少文件打开校验:未判断
fopen是否成功,若文件路径错误或文件不存在,后续读取操作会直接出错。
修复后的代码
#include <stdio.h> #include <stdlib.h> #define EMPTY '-' #define HUMAN 'H' #define ZOMBIE 'Z' // Function Prototypes char** read_map_from_txt(const char* filename, int *width, int *height); int main(int argc, char **argv) { int width, height; char *filename[50] = argv[0]; char **grid = read_map_from_txt(filename, &width, &height); return 0; } char** read_map_from_txt(const char* filenamee, int *width, int *height) { char filename[30] = "maps/map_1.txt"; FILE *file = fopen(filename, "r"); char line[100]; // 检查文件是否成功打开 if (!file) { printf("Failed to open file!\n"); return NULL; } // 正确读取宽度:将数值存入指针指向的变量,校验读取结果 if (fscanf(file, "%d", width) != 1) { printf("Failed to read width!\n"); fclose(file); return NULL; } printf("w - %d\n", *width); // 正确读取高度 if (fscanf(file, "%d", height) != 1) { printf("Failed to read height!\n"); fclose(file); return NULL; } printf("h - %d\n", *height); // 跳过fscanf残留的换行符,避免fgets读取空行 getchar(); while(fgets(line, sizeof(line), file) != NULL) { printf("%s", line); } fclose(file); return NULL; }
修复说明
- 修正
fscanf逻辑:直接将指针width/height传入fscanf,读取到的整数会自动存入指针指向的变量;通过判断返回值是否为1,确保成功读取目标整数。 - 修正
printf格式:使用*width/*height获取指针指向的实际数值,统一用%d格式符打印。 - 添加文件校验:提前判断文件是否打开成功,避免无效读取操作。
- 处理换行残留:用
getchar()跳过fscanf读取整数后残留的换行符,确保fgets能正确读取后续内容。
内容的提问来源于stack exchange,提问作者SUPERoya
相关产品推荐
相关产品推荐

