What is the proper way to read a text file into an array of lines? I found the following on Rosetta Stone:
string[] readLines(string filename) {
auto f = File(filename);
scope(exit) f.close();
string[] lines;
foreach (str; f.byLine) {
lines ~= str.idup;
}
return lines;
}
but it looks like it’s doing one array resize per line, which is pretty inefficient. I could keep track of the number of lines read in and resize the array via the standard doubling method
int i = 0;
foreach (str; f.byLine) {
if (lines.length <= i + 1) {
lines.length = lines.length * 2 + 1;
}
lines[i] = str.idup;
i++;
}
lines.length = i;
but that’s enough boilerplate code that I have to wonder if I’m not just overlooking something in the standard library that already does this for me.
Edit: giving fwend’s comment more visibility: this article describes in detail how the array allocator works, and why appending is handled efficiently by the runtime
Actually, D will double the array’s reserved space whenever it runs out of room, so you don’t need to do it by hand. There is a lot of information about D’s arrays here