我正在做一个小项目,我想知道为什么这段代码会导致我的程序崩溃。
PLAYER_FILE_PATH -- "player.txt"
sprite=yoshi.bmp
width=64
height=64
frames=8
alignment=1
animate=1
程序
FILE *pfile = fopen(PLAYER_FILE_PATH, "r");
if (!pfile)
{
debug_printf("could not open player file for reading!\n");
return;
}
fscanf(pfile, "sprite=%s\n\
width=%d\n\
height=%d\n\
frames=%d\n\
alignment=%d\n\
animate=%d",
player_entity.entity_sprite.imgloc,
&player_entity.entity_sprite.width,
&player_entity.entity_sprite.height,
&player_entity.entity_sprite.frames,
&player_entity.entity_sprite.oscdir,
&player_entity.entity_sprite.osc);
fclose(pfile);
最佳答案
我们需要查看您对 player_entity 的定义才能确定。您可能没有正确定义“imgloc”,它需要指向一些安全分配的内存。例如,除非正确初始化 imgloc,否则以下定义将进行核心转储:
struct {
struct {
char *imgloc;
int width;
int height;
int frames;
int oscdir;
int osc;
} entity_sprite;
} player_entity;
如果你用类似的东西替换上面的 imgloc 行,这个核心转储将被避免
char imgloc[100];
但是,我会非常小心地使用 fscanf 读取字符串,因为如果字符串太长,它会溢出给定的缓冲区。也许只对字符串部分尝试 fgets,对其余部分尝试 fscanf。
关于c - fscanf 正在崩溃程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874581/