Skip to content

Instantly share code, notes, and snippets.

@JISyed
Created December 7, 2013 04:24
Show Gist options
  • Save JISyed/7837265 to your computer and use it in GitHub Desktop.
Save JISyed/7837265 to your computer and use it in GitHub Desktop.
A little helper function to load an OpenGL shader file (can be any text formatted file) to a C-String. The returned string has to be deleted by the caller when not needed anymore. You need: #include <iostream> #include <fstream>
const char* ReadShaderFileToMemory(const char* filePath)
{
const char * shaderFileBuffer = NULL;
std::ifstream inSdrFileStream(filePath);
if(inSdrFileStream)
{
// Get length of shader file by seeking and telling (offset of 0)
inSdrFileStream.seekg(0, inSdrFileStream.end);
unsigned long fileLength = (unsigned long) inSdrFileStream.tellg() + 1;
inSdrFileStream.seekg(0, inSdrFileStream.beg);
std::cout << "Shader File: Reading " << fileLength << " chars...\n";
// Read shader file into a memory buffer (array)
char * inputFileBuffer = new char[fileLength];
memset(inputFileBuffer, 0, fileLength);
inSdrFileStream.read(inputFileBuffer, fileLength);
inputFileBuffer[fileLength-1] = 0;
// Close file and print status
if(inputFileBuffer)
{
std::cout << "... Read successfully.\n\n";
std::cout << "---------------------------------\n";
std::cout << inputFileBuffer << std::endl;
std::cout << "---------------------------------\n";
std::cout << std::endl;
inSdrFileStream.close();
}
else
{
std::cout << "... Error: Only " << inSdrFileStream.gcount() << " could be read!\n";
inSdrFileStream.close();
delete [] inputFileBuffer;
return NULL;
}
// Hand over file contents to a const pointer
shaderFileBuffer = inputFileBuffer;
inputFileBuffer = NULL;
}
else
{
std::cout << "Shader File: Error. Not found!" << std::endl;
return NULL;
}
return shaderFileBuffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment