Logo

Programming-Idioms

  • Pascal
  • C#

Idiom #197 Get a list of lines from a file

Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.

using System.IO;
using System.Collections.Generic;
using System.Linq;
        public List<string> GetLines(string _path)
        {
            return File.ReadAllLines(_path).ToList();
        }
uses Classes;
var
  Lines: TStringList;
...
  Lines := TStringList.Create;
  Lines.LoadFromFile(Path);

After the LoadFromFile the lines (in the StringList) are accessible (r/w) through its Strings[] property.
#include <fstream>
std::ifstream file (path);
for (std::string line; std::getline(file, line); lines.push_back(line)) {}

Push new line in lines happens only when std::getline() retrieved data.

file(path) opens file in read-only mode.
file will be closed by destructor

New implementation...
< >
Jadiker