15

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;
}
4

4 回答 4

28
settingsFile.clear();
settingsFile.seekg(0, settingsFile.beg);
于 2013-05-06T07:01:40.333 回答
5

要将文件倒回到它的开头(例如再次读取它),您可以使用ifstream::seekg()更改光标的位置并ifstream::clear()重置所有内部错误标志(否则它会显示您仍在文件末尾)。

其次,您可能需要考虑只读取一次文件并将您需要知道的内容临时存储std::dequestd::list在解析文件时存储。std::vector然后,如果您稍后需要该特定容器,则可以从临时容器构造一个数组(或 )。

于 2013-05-06T07:38:24.923 回答
4

效率低下,使用 astd::vector并只读取一次文件。

vector<string> settings;
ifstream settingsFile("settings.txt");
string setting;
while (getline(settingsFile, setting))
{
    settings.push_back(setting);
}
于 2013-05-06T07:02:18.303 回答
1

只需使用:

settingsFile.seekg(0, settingsFile.beg);

这会将文件指针倒回到开头,因此您可以在不关闭和重新打开的情况下再次阅读它。

于 2013-05-06T07:01:52.563 回答