gpt4 book ai didi

c - 使用 fopen 打开文件进行读取时遇到问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:10 24 4
gpt4 key购买 nike

我是在 linux 下编写 c 语言的新手,所以这可能是个愚蠢的问题,但我在使用 fopen 时遇到了问题。当我遇到这个问题时,我只是用这个非常简单的代码尝试了一下:

#include <stdio.h>
#include<stdlib.h>

int main()
{
FILE *test;

if( fopen("test.txt","r") == NULL )
printf("didnt open");
else
printf("opened!");

fclose(test);
}

test.txt 与此代码和 a.out 位于同一文件夹中。当我调试 a.out 时,我得到:

Breakpoint 1, main () at testit.c:14
14 if( fopen("test.txt","r") == NULL )
(gdb) s
_IO_new_fopen (filename=0x400696 "test.txt", mode=0x400694 "r") at iofopen.c:103
103 iofopen.c: No such file or directory.
(gdb) s
__fopen_internal (filename=0x400696 "test.txt", mode=0x400694 "r", is32=1) at iofopen.c:65
65 in iofopen.c
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
_IO_new_fclose (fp=0x0) at iofclose.c:54
54 iofclose.c: No such file or directory.

我尝试更改路径:if( fopen("/home/h1657/Work/test/test.txt","r") == NULL )。有同样的效果。

如果这是一个基本问题,我很抱歉,但我找不到任何解决方案。

最佳答案

关于 gdb 的消息:

iofopen.c: No such file or directory.

无论如何,即使您的代码是正确的,您也会从 gdb 收到该消息。那是因为您使用的是 step 而不是 next

完整解释如下:

"The step command follows the code into a function call. When stepping, gdb prints each source line before executing it. If you step into a library function, gdb wants to display the source, but those file are not available on the system. The complaint is expected and harmless. If you use the next command instead, it will step over and treat the entire call as a single step."

来自 http://web.stanford.edu/class/cs107/guide_gdb.html

事实上,使用 step 再次尝试 gdb 正确的代码,您将得到相同的消息 iofopen.c: No such file or directory.

关于c - 使用 fopen 打开文件进行读取时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25564864/

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