Reputation: 185
I have an algorithm in C++ (main.cpp) and I use CLion to compile and run it. Algorithm would read strings from text file, but there is a mistake:
Could not open data.txt (file exists and placed in one folder with main.cpp)
How can I fix it and make this file "visible" to CLion?
Upvotes: 8
Views: 11372
Reputation: 196
Continuing with the CMAKE_RUNTIME_OUTPUT_DIRECTORY
CMakeLists variables, I do the following. In the root directory of my project, I create a directory, e.g., out
. Then, in my CMakeLists.txt
I set the CMAKE_RUNTIME_OUTPUT_DIRECTORY
to that directory:
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/out)
Note, that must come before you have
add_executable(YourProject ${SOURCE_FILES})
I might also add that instead of using fopen()
I would keep it more object-oriented by using std::ifstream
:
std::ifstream inFile("data.txt");
// check if it opened without issue...
if (!inFile) {
processError(); // a user-defined function to deal with the issue
} else {
// All is good, carry on...
// and when you're done don't forget
inFile.close();
}
Upvotes: 0
Reputation: 203
Now you can fopen
relatively from working directory.
Upvotes: 4
Reputation: 90
I found another way to solve this problem.
@Lou Franco's solution may affect the project structure. For example, if I deploy code on a server, I should move the resource file to specific directory.
What I do is modify the CmakeLists.txt, on Windows, using
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "D:\\science\\code\\English-Prediction")
CMAKE_RUNTIME_OUTPUT_DIRECTORY is a CMake variable, it assigns the work directory of CLion work directory.
Upvotes: 2
Reputation: 89222
If you are using fopen
or something similar and just passing "data.txt"
, it is assumed that that file is in the current working directory of the running program (the one you just compiled).
So, either
Give a full path instead, like fopen("/full/path/to/data.txt")
, where you use the actual full path
(not preferable), Move data.txt to the directory where CLion runs its compiled programs from.
(for #2, here's a hacky way to get that directory)
char buf[1024]; // hack, but fine for this
printf("%s\n", getcwd(buf, 1024));
Upvotes: 8