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;
}
Splitting the editor (from the tab context menu) allows to have 2 copies of the same file open at the same time.
Using Java Files Class to Read a File Java Files class, introduced in Java 7 in Java NIO, consists fully of static methods that operate on files. Using Files class, you can read the full content of a file into an array. This makes it a good choice for reading smaller files.
You can use fseek() to go back to the beginning of the file and read it again. You need to close the file or call fflush() after adding to the file, to flush the output buffer.
settingsFile.clear();
settingsFile.seekg(0, settingsFile.beg);
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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With