Skip to content

Instantly share code, notes, and snippets.

@YetAnotherMinion
Created January 12, 2015 19:35
Show Gist options
  • Save YetAnotherMinion/e3e1f7a47b48a184aa4c to your computer and use it in GitHub Desktop.
Save YetAnotherMinion/e3e1f7a47b48a184aa4c to your computer and use it in GitHub Desktop.
file buffer duplication using string streams
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
int main(int argc, char* argv[]) {
if(argc != 3) {
std::cerr << "Usage: " << argv[0] << " <filename> <num_iters>" << std::endl;
return 0;
}
int iters = atoi(argv[2]);
std::string filename(argv[1]);
std::ifstream istr(filename);
if (!istr) {
std::cerr << "ERROR: cannot open file " << filename << std::endl;
exit(1);
}
//get the length of the file
istr.seekg(0,std::ios::end);
std:: streampos length = istr.tellg();
istr.seekg(0,std::ios::beg);
std::vector<char> buffer(length);
//read the file into the buffer
istr.read(&buffer[0], length);
//load the file buffer into a string stream
std::stringstream root;
root.rdbuf()->pubsetbuf(&buffer[0],length);
//doing something with a copy of filebuffer
while (iters > 0) {
std::cout << iters << std::endl;
iters--;
// create a copy string
std::stringstream partstr(root.str());
//do work with string stream
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment