Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read a file into an array of lines in d

Tags:

arrays

file-io

d

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

like image 912
Martin DeMello Avatar asked Apr 25 '12 05:04

Martin DeMello


People also ask

How do you read a text file and store it to an array in Java?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader.

How do you read an array file?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.


1 Answers

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

like image 81
ricochet1k Avatar answered Oct 10 '22 23:10

ricochet1k