【发布时间】:2014-05-26 16:53:29
【问题描述】:
我正在为 C 字搜索程序编写一些代码,在编译其中一个文件时,我在 fscanf 函数上遇到分段错误,但我不知道错误在哪里。 我已经搜索过答案,并且我明白在整数变量上我必须初始化它们的值(我已经完成了),并且我必须使用 '&' 引用 fscanf() 中的类型(也完成了)。
这是代码(在 main() 函数中):
int i;
int nl = 0;
int nc = 0;
int a, b, d;
char mat[1000][1000];//character matrix for wordsearch letters
int x[1000], y[1000];
int l, c, n;
printf("Chose the wordsearch you want to use.\n For example: t01.in, t02.in, t03.in, t04.in, (...),t30.in\n");
char wordsearch_file[8];
fgets(wordsearch_file,8,stdin);//user enters f.e. 't01.in'
FILE *stream;
char buffer[1024];
sprintf(buffer, "home/adminuser/Desktop/LA/ETAPA2/sopas/%s", wordsearch_file);
stream = fopen(buffer,"r");
if((fscanf (stream,"%d%d", &nl, &nc)) > 0){ // SEG. FAULT happens here
for(l = 0; l < nl; l++) {
for(c = 0; c < nc; c++)
mat[l][c] = fgetc(stream) != EOF;
fgetc(stream);
}
}
我希望“nl”(行数)读取 3,而“nc”(编号 os 列)读取其他 3。
“t01.in”文件:
3 3
SIA
ORR
EDI
【问题讨论】:
-
您检查文件是否存在并成功打开?您的完整地址开头可能缺少斜杠。
-
buffer包含换行符。所以stream = fopen(buffer,"r");失败了。 -
你是对的。我更改了那部分代码,一切正常。谢谢!
标签: c segmentation-fault scanf