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;
}
It's inefficient, use a
std::vector
and read through the file once only.Just use:
This will rewind file pointer to the very beginning, so you can read it again without closing and reopening.
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 andifstream::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
orstd::list
while you parse the file. You can then construct an array (orstd::vector
) from the temporary container, if you would need that specific container later.