Skip to content

Instantly share code, notes, and snippets.

@klmr
Created June 5, 2017 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/a3e88c0ce102be0d3b2ce52ae83825e5 to your computer and use it in GitHub Desktop.
Save klmr/a3e88c0ce102be0d3b2ce52ae83825e5 to your computer and use it in GitHub Desktop.
Efficiently subset many lines from a text file
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
auto main(int argc, char** argv) -> int {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " file line_numbers\n";
return EXIT_FAILURE;
}
auto const filename = argv[1];
auto const lines_filename = argv[2];
auto lines = std::vector<int>{};
auto lines_file = std::ifstream{lines_filename};
std::copy(
std::istream_iterator<int>{lines_file},
std::istream_iterator<int>{},
std::back_inserter(lines));
std::sort(begin(lines), end(lines));
auto file = std::ifstream{filename};
auto line = std::string{};
auto lineno = int{1};
auto next_line = unsigned{0};
while (std::getline(file, line)) {
if (next_line == lines.size()) break;
if (lineno++ == lines[next_line]) {
std::cout << line << '\n';
++next_line;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment