Skip to content

Instantly share code, notes, and snippets.

@sergnechaev
Last active October 6, 2018 09:29
Show Gist options
  • Save sergnechaev/d788ce3623935efa58e6ef1af668b8af to your computer and use it in GitHub Desktop.
Save sergnechaev/d788ce3623935efa58e6ef1af668b8af to your computer and use it in GitHub Desktop.
C++ read text file to a vector of lines or a string
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
std::vector<std::string> utils::files::readLines(const std::string& filename) {
std::ifstream ifs(filename);
std::vector<std::string> lines;
if (!ifs) {
std::cerr << "Cannot open file: " << filename << std::endl;
} else {
for (std::string line; std::getline(ifs, line); /**/) {
lines.push_back(line);
}
std::cout << std::to_string(lines.size()) << " lines read from [" << filename << "]" << std::endl;
}
return lines;
}
std::string utils::files::readFileToString(const std::string& file) {
std::cout << "Read string from file [" << file << "]" << std::endl;
std::ifstream t(file);
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment