无法使用ifstream将txt文件的最后一部分写入cout [英] Can't write the last part of a txt file to cout using ifstream
问题描述
下面的代码将打印我使用的示例文本文件中的所有文本,除了它的最后一个小片段。我认为这与eof或字节大小有关系我使用不工作,因为我期望。
The code below will print all of the text from the sample text file I'm using except for the last little snippet of it. I think this has something to do with the eof or the byte size I'm using not working as I expect.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
int length;
char* buffer;
//get file stream and open local file.
ifstream stream;
stream.open("SampleFile.txt", ios::binary);
stream.seekg(0, ios::end);
length = stream.tellg();
stream.seekg(0, ios::beg);
//read stream 1024 bytes at a time until all bytes of file are used
buffer = new char[1024];
bool eof = false;
while(!eof)
{
stream.read(buffer, 1024);
cout.write(buffer, 1024);
if(stream.eof())
eof = true;
//cout << i << endl;
//cout.write(buffer, 1024);
}
stream.close();
delete[] buffer;
return 0;
}
我缺少什么?
推荐答案
正如你已经知道的,你的缓冲区大小不正确。另一件事是读取少于1024个字符(如果您的文件没有完全 n * 1024
字节,则会发生在最后)。利用 istream :: gcount
的优势,它提供了最后一次读取的字符数:
As you already know, you have a wrong size of buffer. The other thing is the read of less than 1024 characters (going to happen at the end if your file doesn't have exactly n*1024
bytes). Take the advantage of istream::gcount
which gives you number of characters extracted by last read:
char buffer[1024];
while(stream)
{
stream.read(buffer, 1024);
cout.write(buffer, stream.gcount());
}
这篇关于无法使用ifstream将txt文件的最后一部分写入cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!