fanis deligiannis fanis deligiannis - 14 days ago 5
C++ Question

C++ file not found when debugging from visual studio 2015

My problem is that when doing

Shader* s = new Shader("Shaders\\test.vert", "Shaders\\test.frag");


or

Texture texture("test.png");


visual studio refuses to find them, yet when opening the .exe file everything is working properly. Doing

Shader* s = new Shader("C:\\Users\\Public\\Google Drive\\vs projects\\Engine\\Debug\\Shaders\\test.vert", "C:\\Users\\Public\\Google Drive\\vs projects\\Engine\\Debug\\Shaders\\test.frag");


does fix the problem for visual studio, but it's not really what I am looking for.

The way I am reading files:

static std::string read_file(const char* path)
{
FILE* file = fopen(path, "rt");
fseek(file, 0, SEEK_END);
unsigned long length = ftell(file);
char* data = new char[length + 1];
memset(data, 0, length + 1);
fseek(file, 0, SEEK_SET);
fread(data, 1, length, file);
fclose(file);

std::string result(data);
delete[] data;

return result;
}


I have made sure I am running the project in debug(x86) mode. Any solutions?

Answer

It's because the working directory of a C++ project in Visual Studio will be set to project directory when run from Visual Studio, instead of the directory which contains the executable. Source: Project Settings for a C++ Debug Configuration

Working Directory

  • Specifies the working directory of the program being debugged, relative to the project directory where your EXE is located. If you leave this blank, the working directory is the project directory. For remote debugging, the project directory will be on the remote server

Hence, the absolute path of Shaders\test.vert is

${path_to_your_project}\Shaders\test.vert

in your case, it's

C:\Users\Public\Google Drive\vs projects\Engine\Shaders\test.vert

or

C:\Users\Public\Google Drive\vs projects\Engine\{project_name}\Shaders\test.vert

if Engine is a solution folder

Simply move your file to the correct directory (the project directory), your code will work.