全局文件指针声明存在一些问题,因此我遇到了段错误。 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;
}
最佳答案
GDB gives the following output after executing the first fopen()
(gdb) p in_fp $1 = (FILE *) 0x0
(gdb) p *in_fp Cannot access memory at address 0x0
这意味着您的文件没有正确打开,或者更具体地说,source_code.txt 没有打开以供阅读。
由于您没有在打开命令中包含路径,请确保它们位于当前工作目录(您从中执行二进制文件的目录)并确保您具有读/写权限。
对于 fopen()
您可以检查生成的文件句柄是否为 NULL,如果是则打印错误消息:
in_fp = fopen(SOURCE_CODE, "r");
if(in_fp == NULL) {
perror("Failed to open the source");
return EXIT_FAILURE;
}
例如,如果文件不存在,您将得到如下内容:
Failed to open the source: No such file or directory
关于c - C中的全局文件指针声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228627/