Search code examples
cgccpathgdbfilepath

Is there a way to do fopen with relative path with gdb?


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:

  1. compiling the code with gcc and then running it with ./a
  2. using the gdb build & run on vscode, the settings are exactly from https://medium.com/@GorvGoyl/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

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.


Solution

  • 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);
    }
    

    read documentation of printf(3) and of exit(3) before using them.

    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.