Karnivaurus
Karnivaurus

Reputation: 24121

Loading a file with a relative path in Qt Creator

I am writing a C++ program using Qt Creator 3.1.1 in Ubuntu 14.04. This code uses an existing library which loads a file from disk, by passing a string representing a path to that file. The trouble I am having is that when the string represents an absolute path, the file loads fine, but when the string represents a relative path, it fails to load, saying that it cannot find the file.

My project has source files at /home/karnivaurus/project/src, and build files at /home/karnivaurus/project/build. I have placed a copy of the file mesh.stl in each of these directories, and also in the project root directory /home/karnivaurus/project. But when I pass the string ../src/mesh.stl, ../build/mesh.stl, or ../mesh.stl, it fails to load. It also fails with /../src/mesh.stl, /../build/mesh.stl, and../src/mesh.stl, ../build/mesh.stl, or ../mesh.stl.

However, it does find the file if I pass the strings /home/karnivaurus/project/src/mesh.stl, /home/karnivaurus/project/build/mesh.stl or /home/karnivaurus/project/mesh.stl.

Why is this? Is it a problem with my understanding of relative paths in C++? Or is it something I need to configure in Qt Creator? In my Qt Creator settings, I have the working directory set to /home/karnivaurus/project/build.

The exact line I use to load the mesh is:

const aiScene* mesh = MeshLib::loadMesh("../mesh.stl");

And the corresponding error message is:

Failed opening file '/mesh.stl' for reading: No such file or directory

This error message is suspicious to me because /mesh.stl is not equivalent to ../mesh.stl...

Upvotes: 1

Views: 4266

Answers (1)

Georgy Pashkov
Georgy Pashkov

Reputation: 1304

Looks like you've already made sure that the working directory is correct. Given that that possibility is eliminated, what's left is a bug in the 3rd party library.

You can construct an absolute path using Qt:

QString meshPath = QDir().filePath("../mesh.stl"); 
const aiScene* mesh = MeshLib::loadMesh(meshPath.toLatin1().data());

This could serve as work-around until developers of the library fix the bug.

Upvotes: 1

Related Questions