被这个问题折磨了两个小时。。。特意发帖记录一下
水平有限,如果有错希望各位指正。
引用
https://blog.csdn.net/u013094443/article/details/48679947
http://blog.sina.com.cn/s/blog_7eb23c070102wi9l.html
https://zhidao.baidu.com/question/1946793394897830268.html
https://blog.csdn.net/zhi11235813/article/details/80741338
当前项目路径
当前项目目录 :.vcxproj
文件所在的目录,测试项目结构如下图
要打开res->shader->vertex.shader
文件,无论.cpp
文件在哪,直接找到当前目录"./",接着打开同级目录 res
main.cpp 中测试代码如下,可以正确打开
const char* vertPath = "./res/shader/vertex.shader";
std::string vertexCode;
std::ifstream vShaderFile;
// 确保ifstream可以抛出异常
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try{
// 打开文件
vShaderFile.open(vertexPath, std::ios::binary);
std::stringstream vShaderStream;
// 读取文件内容到sstream中
vShaderStream << vShaderFile.rdbuf();
// 关闭
vShaderFile.close();
// sstream转为string
vertexCode = vShaderStream.str();
}
catch(std::ifstream::failure e)
{
std::cout << "ERROR...." << std::endl;
}
或者直接写"res/shader/vertex.shader"
也是可以的,但未必所有的编译器都支持自动补全。
当前文件路径
默认情况下,include 的路径是当前文件路径,而不是.vcxproj
文件所在的当前项目路径。
仍然是上面的结构,如果在 main.cpp
中想包含 shader.h
文件,则需要返回到上一级目录,也就是 include 所在的目录。
如图,只有添加了../
才能在main.cpp
中访问到include
文件夹
这样就比较混乱,如何避免这个情况呢。
解决方案
在项目属性 -> C/C++ -> 常规 -> 附加包含目录 中添加 “./”
也就是让 include 的默认路径以 当前项目路径 为起点
添加后就可以正常使用了,此时三种目录似乎均可以正常使用(以当前文件为起点,显式以当前项目为起点,隐式以当前项目为起点)