无法使用 ifstream 将 txt 文件的最后一部分写入 cout
Can't write the last part of a txt file to cout using ifstream
下面的代码将打印我使用的示例文本文件中的所有文本,除了它的最后一小段。我认为这与我使用的eof或字节大小不像我期望的那样工作有关。
#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
的优势,它给出了上次读取提取的字符数:
char buffer[1024];
while(stream)
{
stream.read(buffer, 1024);
cout.write(buffer, stream.gcount());
}
1)您没有正确计算最终缓冲区的大小。
2)您没有正确识别所有可能的错误情况。
试题:
while(stream) {
stream.read(buffer, 1024);
cout.write(buffer, stream.gcount());
}
p 。如果您真的想将命名文件复制到标准输出,有一个更简单的方法:
ifstream stream("SampleFile.txt", ios::binary);
std::cout << stream.rdbuf();
看起来问题是,您的最后一次读取并不恰好是您的缓冲区的大小。你得把它当作特例来处理。详细信息请参见http://www.cplusplus.com/reference/iostream/istream/read/
哦,看起来你的缓冲区是8字节长,但你读了1024字节。这是不好的。
既然知道文件的大小,为什么不立即读取整个文件呢?
<>之前Buffer = new char[length];流。读取(buffer, length);cout。Write (buffer, length);删除[]缓冲区;相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- lower_bound()返回最后一个元素
- 从控制台中删除最后打印的元素
- C++:如何使函数只返回作为列表一部分的字符串
- 获取向量C++中第一个值和最后一个值的和
- std::sort()函数无法对向量的一部分进行排序
- 获取用C/C++打印的最后一个字符串
- 读取最后一行代码算法 - c++ 时出现问题
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- 如何在最后一步使用CryptDecrypt解决NTE_BAD_DATA
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 如何在Qt TableView中将列的宽度调整为数据并将最后一部分拉伸在一起
- Qt QString Remove的最后一部分是什么
- 删除url的最后一部分
- 无法使用 ifstream 将 txt 文件的最后一部分写入 cout
- 如何找出传递路径的最后一部分是文件、目录还是掩码
- C++帮助 - 我似乎无法弄清楚此代码的最后一部分