Kerwin Xiao
Kerwin Xiao

Reputation: 323

Clion -- why do I need to type the full path?

I'm writing a small game from CS106L course reader. I use Clion and Window.
I put level.txt in the direct location with main.cpp etc. But Why do I need type the full name to read the file rather than just type level.txt? The core code is:
```c

void readCorrectFile(ifstream& input) {
    // Read the user's prompt until user prompt the right file.
    while (true) {
        cout << "Enter the file name: ";
        string filename;
        getline(cin, filename);

        // Find if it's a valid name
        input.open(filename.c_str());
        if (input.is_open()) {
            return;
        }

        // Show info about read file.
        cout << "Sorry, we cannot find: " << filename << endl;
        input.clear();
    }
}

``` The output is :
error

The struct of my project: error2

Upvotes: 1

Views: 964

Answers (2)

Ardavel
Ardavel

Reputation: 1515

As Dan said, a relative path should be relative to your .exe file location. In case you build and run your program from IDE, the .exe file is created inside some CLion directories. If you would like to have more control of your .exe file location, you can add the following line to your CMakeLists.txt (before add_executable I assume).

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "path_to_directory_of_your_exe")

This is something I sometimes do for convenience with using relative paths.

Upvotes: 0

erik258
erik258

Reputation: 16304

Assumedly your current working directory when invoking Snake.exe is not the same as the directory containing level.txt. Programs executed at the command line inherit their current working directory from the shell that executed them.

Upvotes: 3

Related Questions