为什么rdbuf()不打印任何内容

Why does rdbuf() not print anything?

本文关键字:打印 任何内 rdbuf 为什么      更新时间:2023-10-16

在以下示例中,

ifstream myFile;
myFile.open("example.txt", ios::binary);
cout << myFile.rdbuf() << endl; 
myFile.close();

文件的内容将全部打印在一行中。你也可以这样做:

ifstream myFile;
myFile.open("example.txt", ios::binary);    
unsigned char character = myFile.get();
while(myFile){
    cout << "one character = ";
    cout << character;
    character = myFile.get(); //gets each individual character, 1 at a time
}
myFile.close();

它将打印文件的内容,一次打印一个字符。但是,如果您尝试一个接一个地(按任何顺序)执行这些方法,那么实际上只有一个方法会打印任何内容。有人能解释一下为什么在下面的例子中,对rdbuf()的调用不会打印文件的内容吗?

ifstream myFile;
myFile.open("example.txt", ios::binary);    
unsigned char character = myFile.get();
while(myFile){
    cout << "one character = ";
    cout << character;
    character = myFile.get(); //gets each individual character, 1 at a time
}
cout << myFile.rdbuf() << endl; 
myFile.close();     

谢谢!

从流中读取时,读取位置会递增。逐个字符读取整个文件后,读取位置位于文件末尾。在这种情况下,rdbuf()(读取缓冲器)没有其他感兴趣的内容。

如果要使用rdbuf()再次打印文件,可以在尝试打印之前使用myFile.seekg(0, std::ios::beg);设置读取位置。在这个特定的示例中,可能已经设置了错误位,因此在移动读取指针之前,您可能需要执行myFile.clear()