关于使用C ++ istream_iterator从文件中读取部分数据的事情

时间:2012-02-17 21:33:04

标签: c++ file-io stl

目标:有一个文本文件(在硬盘上),包含用某种分隔符划分的整数。

示例:

5245
234224
6534
1234

我需要将它们读入STL容器。

int main(int argc, char * argv[]) {
  using namespace std;

  // 1. prepare the file stream
  string fileName;
  if (argc > 1)
    fileName = argv[1];
  else {
    cout << "Provide the filename to read from: ";
    cin >> fileName;
  }
  unique_ptr<ifstream, ifstream_deleter<ifstream>> ptrToStream(new ifstream(fileName, ios::out));
  if (!ptrToStream->good()) {
    cerr << "Error opening file " << fileName << endl;
    return -1;
  }

  // 2. value by value reading will be too slow on large data so buffer data
  typedef unsigned int values_type;
  const int BUFFER_SIZE(4); // 4 is for testing purposes. 16MB or larger in real life
  vector<values_type> numbersBuffer(BUFFER_SIZE);
  numbersBuffer.insert(numbersBuffer.begin(), istream_iterator<values_type>(*ptrToStream), istream_iterator<values_type>());
  // ...

此代码的主要缺点是如何在文件大小非常大时处理问题,因此我无法将所有内容存储在内存中? 我也不想使用push_back,因为与区间insert相比它效率不高。


所以,问题是:如何使用STL有效地从文件中读取BUFFER_SIZE个元素?

2 个答案:

答案 0 :(得分:4)

限制从输入迭代器读取的方法是创建一个包装器,它计算到目前为止处理的元素数量,并将其结束迭代器与此数字进行比较。通常这样做并不是一件容易的事情,专门为std::istream_iterator<T>做这件事不应该太难。也就是说,我认为最简单的方法就是:

std::vector<T> buffer;
buffer.reserve(size);
std::istreambuf_iterator<T> it(in), end;
for (std::vector<T>::size_type count(0), capacity(size);
     it != end && count != capacity; ++it, ++count) {
    buffer.push_back(*it);
}

我意识到你不想push_back(),因为据说它很慢。但是,与I / O操作相比,我怀疑您是否能够测量较小的开销,尤其是对于I / O库的典型实现。

使用包装迭代器的示例来解决问题:下面是std::istream_iterator<T>的计数包装器的示例。有许多不同的方法可以做到,这只是其中之一。

#include <iostream>
#include <iterator>
#include <vector>
#include <sstream>

template <typename T>
class counted_istream_iterator:
    public std::iterator<std::input_iterator_tag, T, std::ptrdiff_t>
{
public:
    explicit counted_istream_iterator(std::istream& in): count_(), it_(in) {}
    explicit counted_istream_iterator(size_t count): count_(count), it_() {}

    T const& operator*() { return *this->it_; }
    T const* operator->() { return it_->it_.operator->(); }
    counted_istream_iterator& operator++() {
        ++this->count_; ++this->it_; return *this;
    }
    counted_istream_iterator operator++(int) {
        counted_istream_iterator rc(*this); ++*this; return rc;
    }

    bool operator== (counted_istream_iterator const& other) const {
        return this->count_ == other.count_ || this->it_ == other.it_;
    }
    bool operator!= (counted_istream_iterator const& other) const {
        return !(*this == other);
    }
private:
    std::ptrdiff_t           count_;
    std::istream_iterator<T> it_;
};

void read(int count)
{
    std::istringstream in("0 1 2 3 4 5 6 7 8 9");
    std::vector<int>   vec;
    vec.insert(vec.end(), counted_istream_iterator<int>(in),
               counted_istream_iterator<int>(count));
    std::cout << "size=" << vec.size() << "\n";
}

int main()
{
    read(4);
    read(100);
}

答案 1 :(得分:0)

有可能解决我的问题:

// 2. value by value reading will be too slow on large data so buffer data
typedef unsigned int values_type;
const int BUFFER_SIZE(4);
vector<values_type> numbersBuffer;
numbersBuffer.reserve(BUFFER_SIZE);
istream_iterator<values_type> begin(*ptrToStream), end;
while (begin != end) {
  copy_n(begin, BUFFER_SIZE, numbersBuffer.begin());
  for_each(numbersBuffer.begin(), numbersBuffer.end(), [](values_type const &val){ std::cout << val << std::endl; });
  ++begin;
}

但它有一个缺点。如果输入文件包含以下内容:

8785
245245454545
7767

然后将读取8785,但245245454545和7767将不会,因为245245454545无法转换为unsigned int。错误将是沉默的。 :(