繁体   English   中英

ifstreams和rdbuf()的怪异行为

[英]Weird behavior with ifstreams and rdbuf()

我注意到,在ifstream上使用.rdbuf()似乎会以某种方式对其进行更改。 以下代码应显示该问题。

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {
    ifstream ifs("Sample.csv");
    cout << "Reading buffer: " << endl;
    cout << ifs.rdbuf(); // Outputs buffer as expected
    cout << "Reading buffer again: " << endl;
    cout << ifs.rdbuf(); // Returns nothing

    return 0;
}

这让我感到困扰的原因是我目前正在尝试使用ofstream ofs; ofs << ifs.rdbuf()将一个文本文件的内容复制到另一个文件中ofstream ofs; ofs << ifs.rdbuf() ofstream ofs; ofs << ifs.rdbuf() 这工作得很好,但是从使阅读ifs使用getline(ifs, str)失败,有效地“破”的流。

这不是特别“怪异”; 这与您每天看到的流行为相同。 rdbuf不像std::stringstream::str()也不是魔术,它是指向缓冲区的指针,然后您的cout正在读取内容,就像您自己从原始流中读取内容一样:

std::stringstream ss("1");
int x;
if (ss >> x)
   cout << x;
if (ss >> x)   // doesn't work a second time; "1" is already extracted
   cout << x;

由于您的流是文件流,因此可以从头开始查找它(从本质上说,它对基础缓冲区也是如此)。

ifs.rdbuf()返回一个指向ifs的相应流缓冲区对象的指针。 通过<<重载将其发送到std::cout从流中获取信息,直到到达缓冲区的末尾( eof )。 再次调用.rdbuf()将返回“ nothing”,因为在缓冲区的末尾没有任何要读取的内容。 通过调用ifs.seekg (0);将缓冲区查找位置显式重置为零ifs.seekg (0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM