Created
June 5, 2017 12:40
-
-
Save klmr/a3e88c0ce102be0d3b2ce52ae83825e5 to your computer and use it in GitHub Desktop.
Efficiently subset many lines from a text file
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 <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