C++读写文本文件


std::string readText(std::string &filename)
  {
    std::string shaderCodeStr("");
    std::ifstream shaderFile;
    shaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try
    {
      shaderFile.open(filename, std::ios::in);
      std::stringstream shaderStream;
      shaderStream << shaderFile.rdbuf();
      shaderFile.close();
      shaderCodeStr = shaderStream.str();
    }
    catch (std::ifstream::failure e)
    {
      std::cout << "read shader fail: " << e.what() << std::endl;
    }
    // Compile Vertex Shader
    // const char *shaderCodeChar = shaderCodeStr.c_str();
    // return shaderCodeChar;
    return std::move(shaderCodeStr);
  }


---------------------------------------------------------------------------------------------------------------------------------------------

参考:http://www.icodebang.com/article/338709

int Shader::GetShaderFromFile(const GLchar* vertex_shader_path, const GLchar* fragment_shader_path, std::string *vertex_shader_code, std::string *fragment_shader_code)
{
    std::ifstream vertex_shader_file;
    std::ifstream fragment_shader_file;
    vertex_shader_file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
    fragment_shader_file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
    try
    {
        vertex_shader_file.open(vertex_shader_path);
        fragment_shader_file.open(fragment_shader_path);
        std::stringstream vertex_shader_stream, fragment_shader_stream;
        vertex_shader_stream << vertex_shader_file.rdbuf();
        fragment_shader_stream << fragment_shader_file.rdbuf();
        vertex_shader_file.close();
        fragment_shader_file.close();
        *vertex_shader_code = vertex_shader_stream.str();
        *fragment_shader_code = fragment_shader_stream.str();
    }
    catch (std::ifstream::failure e)
    {
        std::cout << "Load Shader File Error!" << std::endl;
        return -1;
    }
    return 0;
}



---------------------------------------------------------------------------------------------------------------------------------------------

posted @ 2022-12-24 09:39  ParamousGIS  阅读(33)  评论(0编辑  收藏  举报