I have a C++ program which reads a specific line from a file based on the index of that line. The index is calculated elsewhere in the program. My question is: can I open a file (i.e., a .txt) and read a line specified by its index?
So far, I have the following code:
#include <iostream>
#include <fstream>
std::string getLineByIndex(int index, std::fstream file)
{
int file_index = 0;
std::string found_line;
for( std::string line; std::getline(file, line); )
{
if (index == file_index)
{
found_line = line;
break;
}
file_index++;
}
return found_line;
}
This linear search will of course become less efficient as the number of lines in the file scales. Therefore, is there a more efficient way to read a line from a file using its index? Does the answer change if each line in the file is the exact same length?
ignoreevery line before the one you need.getLineByIndexis called very often, you could iterate once the file and remember the offset in the file of each line beginning, which will allow you to access to it directly after.