'How to return the directory of the cpp file?

I am trying to return the path of the cpp file I am running. Does anyone know a method or a way to implement this? For example lets say I have this file test.cpp at the path in my computer "C:\Programming\Visual Studio\Test\Test\test.cpp".

Is there a way to get this path without manually typing it? I am trying to determine a method of using c++ to return this path.

For my ftp program I need to get the list of .txt, .pdf, .etc files, which are located at the same path as the .cpp file. This is why I want the .cpp path and not the .exe path.

Any suggestions?



Solution 1:[1]

What about this??

#include<iostream>
#include <string>
using namespace std;

int main()
{
    string file_path = __FILE__;
    string dir_path = file_path.substr(0, file_path.rfind("\\"));
    cout<<dir_path<<endl;

    return 0;
}

Solution 2:[2]

As you state in comments:

"... but for my ftp program I need to get the list of .txt, .pdf, etc. files, which are located at the same path as the .cpp file."

You should have a kind of resource directory defined, that is created when your application is installed, and where your .txt, .pdf, etc. files will be copied by the installation process.

This way implies you have an installation process (which could be the simplest form, by just creating and extracting a .zip archive), that bundles the executable .exe file along these resource files, to be installed on the target machine. Usually, you won't include the source files there.

It's actually a bad idea, to refer to the location of your source .cpp file in this case, since the finally installed program usually doesn't have a notion of the source it was compiled from. Also the program may be installed on a machine with a different environment (especially development environment) from yours.

A better entry point for a generic installation path, is to refer relative to the path that's given you with the argv[0] argument of your main() program entry. It provides you with the full path of your installed executable file.

For the rest, use the operations available from e.g. the boost::filesystem library to manipulate path and file names in a portable way, as mentioned in comments.

Solution 3:[3]

Linux:

#include <string>
#include <iostream>

int main()
{
    std::string file {__FILE__};
    std::string directory {file.substr(0, file.rfind("/"))};
    
    std::cout << directory << std::endl;
    return 0; 
}

This would give you the directory containing the source file, relative to where its being built.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SHR
Solution 2
Solution 3 simplename