Created
November 21, 2012 09:43
-
-
Save yenliangl/4124014 to your computer and use it in GitHub Desktop.
Read file by ifstream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fstream> | |
#include <sstream> | |
#include <vector> | |
int main() | |
{ | |
std::ifstream file("Plop"); | |
if (file) | |
{ | |
/* | |
* Get the size of the file | |
*/ | |
file.seekg(0,std::ios::end); | |
std::streampos length = file.tellg(); | |
file.seekg(0,std::ios::beg); | |
/* | |
* Use a vector as the buffer. | |
* It is exception safe and will be tidied up correctly. | |
* This constructor creates a buffer of the correct length. | |
* | |
* Then read the whole file into the buffer. | |
*/ | |
std::vector<char> buffer(length); | |
file.read(&buffer[0],length); | |
/* | |
* Create your string stream. | |
* Get the stringbuffer from the stream and set the vector as it source. | |
*/ | |
std::stringstream localStream; | |
localStream.rdbuf()->pubsetbuf(&buffer[0],length); | |
/* | |
* Note the buffer is NOT copied, if it goes out of scope | |
* the stream will be reading from released memory. | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment