如何读取多个块中的文件,直到EOF(C ++) [英] How to read a file in multiple chunks until EOF (C++)

查看:116
本文介绍了如何读取多个块中的文件,直到EOF(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这里是我的问题:我想做一个程序从文件读取数据块。让我们说,每个块1024字节。
所以我读取第一个1024字节,执行各种操作,然后打开下一个1024字节,而不读取旧的数据。

So, here's my problem: I want to make a program that reads chunks of data from a file. Let's say, 1024 bytes per chunk. So I read the first 1024 bytes, perform various operations and then open the next 1024 bytes, without reading the old data. The program should keep reading data untile the EOF is reached.

我目前正在使用此代码:

I'm currently using this code:

std::fstream fin("C:\\file.txt");

vector<char> buffer (1024,0); //reads only the first 1024 bytes
fin.read(&buffer[0], buffer.size());

但是如何读取下一个1024字节?我在使用for循环,但我真的不知道如何。我完全是C ++的noob,所以如果有人可以帮助我,这将是巨大的。谢谢!

But how can I read the next 1024 bytes? I was thinking by using a for loop, but I don't really know how. I'm totally a noob in C++, so if anyone can help me out, that would be great. Thanks!

推荐答案

您可以使用循环:

std::ifstream fin("C:\\file.txt", std::ifstream::binary);
std::vector<char> buffer (1024,0); //reads only the first 1024 bytes

while(fin.read(buffer.data(), buffer.size())) {
    std::streamsize s=fin.gcount();
    ///do with buffer
}



EDITED



http://en.cppreference.com/w/cpp/ io / basic_istream / read

这篇关于如何读取多个块中的文件,直到EOF(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆