the best would be fetching text file size and just read buffer into a string, that should do i think..
c++ count lines in txt file and then read these lines without reopening a file
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
bool LoadData(std::string &data, const std::string &filename)
{
std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::ate);
if(file.is_open())
{
std::streampos size(file.tellg());
file.seekg(0, std::ios::beg);
data.reserve(size);
data.append((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
std::cout << data << "\n";
return true;
}
else
std::cout << "Couldn't load " << filename << "\n";
return false;
}
std::size_t GetLines(const std::string &data)
{
std::size_t lines(0);
for(std::size_t length(0); length != std::string::npos;)
{
length = data.find("\n", length+1);
if(length != std::string::npos)
++lines;
}
return lines;
}
std::size_t PutInVecAndGetLines(const std::string &data, std::vector<std::string> &strVec)
{
for(std::size_t length(0), prev; length != std::string::npos;)
{
prev = length;
length = data.find("\n", prev + 1);
if(length != std::string::npos)
strVec.push_back(data.substr(prev, length - prev));
}
return strVec.size();
}
not sure how efficient it is but this would do it i put a line counter in and a linecounter/vector inserter there
std::vector<std::string> getLinesFromFile(const std::string& fname) {
std::ifstream file(fname);
if(!file) {throw std::runtime_error("getLinesFromFile() - Failed to open file.");}
std::stringstream data;
data << file.rdbuf();
file.close();
std::vector<std::string> lines;
while(data) {
lines.emplace_back();
std::getline(data, lines.back());
}
lines.pop_back();
return lines;
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement