2

Consider project in ~/my/computer/my_project with files:

  • main.cpp
  • input

We want the project to be usable on ~/your/computer so we use relative paths when dealing with file streams:

// main.cpp
#include <iostream>
#include <fstream>

int main ()
{
    std::ifstream stream("input");
    
    if (!stream.is_open())
    {
        std::cout << "No file detected" << std::endl;
    }
    
    stream.close();
}

This works when the user executes the program in the my_project directory, but fails otherwise (prints No file detected, which isn't desired).

How to make a program work regardless of the user's present working directory when using file streams like this?

Elliott
  • 2,603
  • 2
  • 18
  • 35
  • 1
    `std::ifstream stream("/the/path/to/my/computer/my_project/input");` ? – KamilCuk Sep 04 '21 at 19:27
  • @KamilCuk, I said in the question that `We want the project to be usable on ~/your/computer so we use relative paths` – Elliott Sep 04 '21 at 20:05
  • The absolute path will also be usable in that path. The best usual solution is to pass the path as an argument - that way, user can use any path he desires. – KamilCuk Sep 04 '21 at 20:12
  • @KamilCuk, sorry, I don't understand your answer? How would one pass in the path as an argument? Surely not by requesting the user to do that? Or do you mean using, say, a `Makefile` command to pass it in? – Elliott Sep 04 '21 at 20:19
  • Just like `cd /dir` you would do `./your_program /dir`. `Surely not by requesting the user to do that?` Specifically by requesting the user to do that, just like `cd` does - request user to put path as an argument. – KamilCuk Sep 04 '21 at 20:20

1 Answers1

3

You need to build a relative path from the location of your executable file.

This depends on the OS, and here are a few ways to do that: Finding current executable's path without /proc/self/exe

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27