How to read same file twice in a row

2019-01-19 13:46发布

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

标签: c++ file-io
4条回答
霸刀☆藐视天下
2楼-- · 2019-01-19 14:05

It's inefficient, use a std::vector and read through the file once only.

vector<string> settings;
ifstream settingsFile("settings.txt");
string setting;
while (getline(settingsFile, setting))
{
    settings.push_back(setting);
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-19 14:06
settingsFile.clear();
settingsFile.seekg(0, settingsFile.beg);
查看更多
相关推荐>>
4楼-- · 2019-01-19 14:12

Just use:

settingsFile.seekg(0, settingsFile.beg);

This will rewind file pointer to the very beginning, so you can read it again without closing and reopening.

查看更多
beautiful°
5楼-- · 2019-01-19 14:18

To rewind the file back to its beginning (e.g. to read it again) you can use ifstream::seekg() to change the position of the cursor and ifstream::clear() to reset all internal error flags (otherwise it will appear you are still at the end of the file).

Secondly, you might want to consider reading the file only once and storing what you need to know in a temporary std::deque or std::list while you parse the file. You can then construct an array (or std::vector) from the temporary container, if you would need that specific container later.

查看更多
登录 后发表回答