When I wanted to use fopen() to read a file in Debugging, fopen() always return NULL and I can't locate the error after trying:
- I just run the code, and fopen() works well, getting what I want. (but failed in debugging)
- I am sured that the file (hello.txt) exists
- I write a simple code like:
#include<stdio.h>
int main()
{
FILE *fp;
char str[50];
fp = fopen("F:\\notes\\assign\\bonus\\hello.txt","r"); //this line
fgets(str, 50, fp);
printf("%s", str);
return 0;
}
this code doesn't work too. I make a breakpoint at "this line" and watch how the FILE *fp changes.
before:
fp: 0x00007ff663b31110 {hello.exe!void(* pre_cpp_initializer)()} {_Placeholder=0x00007ff663ac74a4 {hello.exe!pre_cpp_initialization(void)} }
after:
fp: 0x000001b7d6c3eb50 {_Placeholder=0x0000000000000000 }
you can see fopen() returns NULL;
- I also tried freopen() and fopen_s(), but failed too.
For more information:
- I use vscode. my compiler is "clang", my debugger is Windows VS so that I have to lauch vscode in Developer Cmd Prompt.
I would appreciate if anyone can help me. This disturbs me for a long time.
CodePudding user response:
fp = fopen("F:\\notes\\assign\\bonus\\hello.txt","r"); //this line
A failure by fopen()
(and many other standard library functions) will set errno
to an error code indicating the error cause. You can turn that into a proper error message by adding code like this:
if ( fp == NULL )
{
perror( "Failed to open hello.txt" );
exit( 1 );
}
perror()
will append a description of the error cause to the string you have given as argument, and print that to stderr
. If you want to log the error message elsewhere, strerror()
will write the error message to a string buffer.