C++使用迭代器复制文本文件

C++ copying text files with iterators

本文关键字:文本 文件 复制 迭代器 C++      更新时间:2023-10-16

我刚刚找到了一种将带有迭代器的文件复制到另一个文件的方法:

ifstream ifile("file1.txt");
ofstream ofile("file2.txt");
copy(istream_iterator<string>(ifile),
     istream_iterator<string>(),
     ostream_iterator<string>(ofile, " "));

它是有效的,但不幸的是,"file1.txt"中的所有文本在"file2.txt"中只有一行,但在"file1.txt"中有很多行。

我试图在迭代器的循环之间更改字符串:

copy(istream_iterator<string>(ifile),
     istream_iterator<string>(),
     ostream_iterator<string>(ofile, "n"));

但"file2.txt"的结果更糟——每个单词都在不同的行中。

我的问题:有没有任何方法可以用迭代器复制文件,但不会丢失任何信息,或者我应该用getline()来做?

istream_iterator<T> iter(stream)将使用格式化的输入函数,因此++iter在某种程度上等效于:

T t;
stream >> t;

对于string对象,这意味着丢弃任何前导空白,只读取到下一个空白字符。

如果要使用未格式化的操作,请使用istreambuf_iterator<char>(如注释中所述)。

使用迭代器和std::getline():的可能解决方案

#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
#include <algorithm>
// Define a struct and operator>> for reading lines.
//
struct line
{
    std::string buf;
    operator std::string() const { return buf; }
};
std::istream& operator>>(std::istream& a_in, line& a_line)
{
    return std::getline(a_in, a_line.buf);
}
int main()
{
    std::ifstream in("main.cpp");
    std::ofstream out("copy.cpp");
    std::copy(std::istream_iterator<line>(in),
              std::istream_iterator<line>(),
              std::ostream_iterator<std::string>(out, "n"));
    return 0;
}

取消设置ifstream上的跳过空白标记。

ifile.unsetf(ios_base::skipws);

请参阅http://en.cppreference.com/w/cpp/io/ios_base/unsetf.