Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read same file twice in a row

Tags:

c++

file-io

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;
}
like image 995
Celeritas Avatar asked May 06 '13 06:05

Celeritas


People also ask

How do I open the same file twice in Windows?

Splitting the editor (from the tab context menu) allows to have 2 copies of the same file open at the same time.

Can you reread a file in Java?

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.

Can you read a file twice in C?

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.


4 Answers

settingsFile.clear();
settingsFile.seekg(0, settingsFile.beg);
like image 134
1615903 Avatar answered Sep 20 '22 15:09

1615903


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.

like image 23
Marc Claesen Avatar answered Sep 22 '22 15:09

Marc Claesen


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);
}
like image 42
john Avatar answered Sep 22 '22 15:09

john


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.

like image 44
mvp Avatar answered Sep 21 '22 15:09

mvp