gpt4 book ai didi

c - 我如何在这里删除 SEGFAULT?

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:56 27 4
gpt4 key购买 nike

我创建了一个函数来打印文件的内容:

void readFile(char* filename)
{
int c ;
file = fopen(filename, "r");
printf("The contents of the file are:\n");
while((c = fgetc(file)) != EOF)
{
printf("%c", c);
}
return;

其中 file 是一个全局变量。 GDB 给出如下输出:

_IO_getc (fp=0x0) at getc.c:39
39 getc.c: No such file or directory.
(gdb) bt
#0 _IO_getc (fp=0x0) at getc.c:39
#1 0x000000000040075e in readFile ()
#2 0x00000000004006d4 in main ()

但是,文件存在并且我在打印文件内容后 得到了 SEGFAULT。 可能是因为这里的缓冲区 (c) 很小,但我不确定。另外,即使是这种情况,我也不知道该如何解决。谁能建议我如何继续?

编辑我只调用了一次 readFile 函数。这是我的调用函数:

int main(int argc, char* argv[])
{
char * filename;

filename = argv[1];
readFile(filename);
printf("File Handler: %ld", (long)file);

fclose(file);
return 0;
}

最佳答案

您传递的文件名不存在或由于某些其他原因无法打开。通过检查错误来摆脱段错误(为此你也需要 #include <errno.h> and <string.h>:

void readFile(char* filename)
{
int c ;
file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file '%s' : %s\n", filename, strerror(errno));
return;
}
printf("The contents of the file are:\n");
while((c = fgetc(file)) != EOF)
{
printf("%c", c);
}
return;
}

关于c - 我如何在这里删除 SEGFAULT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21277307/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com