简体   繁体   中英

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 :
错误

The struct of my project: 错误2

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM