C ++按块读取文本文件 [英] C++ reading text file by blocks

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

问题描述

我真的没有找到一个满意的答案在谷歌和I / O在C + +是有点棘手。我想要阅读文本文件的块到一个矢量如果可能的话。唉,我不知道如何。我甚至不确定,如果我的无限循环将打破所有的可能性,因为I / O是棘手的。所以,我能够找出的最好的方法是:

I really didn't find a satisfied answer at google and I/O in C++ is a little bit tricky. I would like to read text file by blocks into a vector if possible. Alas, I couldn't figure out how. I am not even sure, if my infinite loop will be break in all possibilities, because I/O is tricky. So, the best way I was able to figure out is this:

char buffer[1025]; //let's say read by 1024 char block
buffer[1024] = '\0';
std::fstream fin("index.xml");
if (!fin) {
    std::cerr << "Unable to open file";        
} else {
    while (true) {          
        fin.read(buffer, 1024);
        std::cout << buffer;
        if (fin.eof())
            break;
    }

}

请注意第二行'\0'。难道不奇怪吗?我可以做更好的事吗?我可以读取数据到向量而不是char数组吗?是否适合直接读入向量?

Please, note the second line with '\0'. Is it not odd? Can I do something better? Can I read the data into the vector instead of char array? Is it appropriate to read into vector directly?

感谢您的回答。

PS。按块读取确实有意义。

PS. Reading by chunks have sense indeed. This code is short but I am storing it in cyclic buffer.

推荐答案

你应该很好的做下面的事情:

You should be fine doing the following

 vector<char> buffer (1024,0);      // create vector of 1024 chars with value 0   
 fin.read(&buffer[0], buffer.size());

向量中的元素保证连续存储,所以这应该工作 - 该向量永远​​不为空。我最近在这里问了一个类似的问题 - 检查从标准的具体细节的答案

The elements in a vector are guaranteed to be stored contiguously, so this should work - but you should ensure that the vector is never empty. I asked a similar question here recently - check the answers to that for specific details from the standard Can I call functions that take an array/pointer argument using a std::vector instead?

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

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