I am trying to do fopen() with relative path. The code is a simple one:
#include <stdio.h>
#include <stdlib.h>
int main (void){
char filename[FILENAME_MAX]="test.txt";
FILE *fin;
if ((fin=fopen(filename,"r"))==NULL)
{
printf("File not found.");
exit(EXIT_FAILURE);
}
else
{
printf("opened!");
}
return 0;
}
I tried 2 methods:
I have tried changing filename into several things and here are the result:
char filename[FILENAME_MAX]="test.txt";
gcc: opened!
gdb: file not found
char filename[FILENAME_MAX]=".\\test.txt";
gcc: opened!
gdb: file not found
char filename[FILENAME_MAX]="C:\\fullfolderpath\\test.txt";
gcc: opened!
gdb: opened!
Is there a way to open the txt file with relative path while using gdb? the files will be stored on the same directory as the source code, and the compiled program.
Use at least perror(3) when fopen(3) fails, and of course read the documentation of these functions.
So code:
if ((fin=fopen(filename,"r"))==NULL)
{
perror(filename);
printf("File not found.\n");
exit(EXIT_FAILURE);
}
Of course, read also the documentation of GCC and of GDB.
I recommend compiling your foo.c
with gcc -Wall -Wextra -g foo.c -o foo
On Linux, consider also using strace(1) (read of course syscalls(2)...) to understand the behavior of your program.
If you use some other operating system or compiler read the documentation of your compiler and of your operating system. For Windows, refer to the WinAPI.