【发布时间】:2013-03-05 16:10:02
【问题描述】:
全局文件指针声明存在一些问题,因此我遇到了分段错误。 GDB 表明它专门出现在 sourceToStream 函数中的 fscanf 行。任何帮助将不胜感激。
#define SOURCE_CODE "source_code.txt"
#define CHARACTER_STREAM "character_stream.txt"
static FILE* in_fp;
static FILE* out_fp;
void sourceToStream() {
char buf;
while(fscanf(in_fp, "%c", &buf) != EOF) {
if (buf == '\%')
while(buf!='\n' && buf !='\r' && buf!=EOF)
fscanf(in_fp, "%c", &buf);
if(buf != '\n' && buf != '\r' && buf != '\t' && buf != ' ')
fprintf(out_fp, "%c", buf);
}
}
int main() {
in_fp = fopen(SOURCE_CODE, "r");
out_fp = fopen(CHARACTER_STREAM, "w");
sourceToStream();
fclose(in_fp);
fclose(out_fp);
return 0;
}
【问题讨论】:
-
fopen()成功了吗? -
我不知道Mike为什么删除了他的评论,但是你为什么不检查
fopen的返回值呢? -
有两个
fscanf。 -
GDB在执行第一个
fopen()(gdb) p in_fp $1 = (FILE *) 0x0 (gdb) p *in_fp Cannot access memory at address 0x0后给出以下输出 -
@user42933,然后
fopen()失败,因为它在失败时返回NULL。始终检查 IO 操作的结果。