如何连续读取两次相同的文件 [英] How to read same file twice in a row

查看:340
本文介绍了如何连续读取两次相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读一个文件一次,找到它包含的行数,然后再次读取它,所以我可以存储每一行​​的一些数据在一个数组。有没有更好的方式阅读文件两次,关闭和再次打开它?这是我得到的,但是害怕它是低效的。

I read through a file once to find the number of lines it contains then read through it again so I can store some data of each line in an array. Is there a better way to read through the file twice than closing and opening it again? Here is what I got but am afraid it's inefficient.

int numOfMappings = 0;
ifstream settingsFile("settings.txt");
string setting;
while(getline(settingsFile, setting))
{
    numOfMappings++;
}
char* mapping = new char[numOfMappings];
settingsFile.close();
cout << "numOfMappings: " << numOfMappings << endl;
settingsFile.open("settings.txt");
while(getline(settingsFile, setting))
{
    cout << "line: " << setting << endl;
}


推荐答案

settingsFile.clear();
settingsFile.seekg(0, settingsFile.beg);

这篇关于如何连续读取两次相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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