Logo

Programming-Idioms

  • Go
  • 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.

#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
import "os"
import "bytes"
func readLines(path string) ([][]byte, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := bytes.Split(b, []byte{'\n'})
	return lines, nil
}

This is an alternative solution, in case you prefer each line as a byte slice (instead of a string)
import "os"
import "strings"
func readLines(path string) ([]string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(b), "\n")
	return lines, nil
}
import "os"
import "slices"
import "strings"
func readLines(path string) ([]string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := slices.Collect(strings.Lines(string(b)))
	return lines, nil
}

strings.Lines returns an iterator.

Warning: each line contains its original terminating newline.
using System.IO;
using System.Collections.Generic;
using System.Linq;
        public List<string> GetLines(string _path)
        {
            return File.ReadAllLines(_path).ToList();
        }

New implementation...
< >
Jadiker