c++ - 从文件读取时字符串损坏

标签 c++

我正在用 OpenGL 做一些实验,我正在尝试加载着色器。它需要 const char* 中的源代码,但由于我是在 C++ 上进行的,所以我可以使用 std::strings,然后调用 str.c_str()。这不是问题 - 当我尝试读取一个文件时,它读取完美,但返回的值是一个损坏的字符串。以下是代码的相关部分:

// inline method on engine.hpp
inline void readFile(std::string filePath, std::string* retValue) 
{
std::ifstream file;
file.open(filePath);

std::string result;

std::string line;
while (!file.eof())
{
    std::getline(file, line);
    result.append(line + "\n");
}

    memcpy(retValue, &result, sizeof(result));
}

// implemented method on engine.cpp
GLint Engine::createShader(std::string vs, std::string fs)
{
GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);

std::string vsSourceStr = "";
std::string fsSourceStr = "";

readFile(vs, &vsSourceStr);
readFile(fs, &fsSourceStr);

const char* vsSource = vsSourceStr.c_str();
const char* fsSource = fsSourceStr.c_str();

//std::string t_vs = readFile(vs);

//const char* vsSource = readFile(vs).c_str();
//const char* fsSource = readFile(fs).c_str();

glShaderSource(vertex, 1, &vsSource, NULL);
glCompileShader(vertex);

glShaderSource(fragment, 1, &fsSource, NULL);
glCompileShader(fragment);

GLint program = glCreateProgram();
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);

if (shaderCompiled(program))
{
    std::cout << "shader successfully compiled" << std::endl;
}
else
{       
    std::cout << "shader not compiled" << std::endl;
    printShaderError(vertex);
    printShaderError(fragment);

    std::cout << "Vertex Shader source:" << std::endl;
    std::cout << vsSource << std::endl;

    std::cout << "Fragment Shader source:" << std::endl;
    std::cout << fsSource << std::endl;
}

return program;
}

这是 Visual Studio 在调试时所说的:http://prntscr.com/4qlnx7

它完美地读取文件,只是使返回值崩溃。我试过它返回结果,使用引用和复制内存,正如您在我的代码中看到的那样。 无论如何谢谢。

最佳答案

这不会像你想的那样:

std::string line;
while (!file.eof())
{
    std::getline(file, line);
    result.append(line + "\n");
}

请使用:

std::string line;
while (std::getline(file, line))
{
    result.append(line + "\n");
}

原因是 eof() 直到文件被读取后才会被触发。这意味着您的 std::getline() 可能已失败(在 EOF)并且您正在使用该错误数据。

参见: C++ FAQ 15.5关于 eof()

关于c++ - 从文件读取时字符串损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26068358/

相关文章:

c++ - 用指针数组递增和递减

c++ - 如何在一个语句下编写一个带有 (a < b < c) 的 for 循环?

c++ - 是否可以将宏函数作为 QMetaMethod 标记?

c++ - 我们是继承接口(interface)还是实现接口(interface)?

c++ - 工厂方法 C++ 实现

带有新宏的 C++ std::make_shared

c++ - 添加typename导致程序编译失败

C++简单多态问题

c++ - 来自 std::_Rb_tree_increment (__x=0x1) 的段错误

c++ - C++中置换组合的库函数