import java.util.*;
import java.lang.Math;
import org.apache.commons.math.fraction.Fraction;
import org.apache.commons.math.fraction.FractionConversionException;

/* Matrix class
 * Handles elementary Matrix operations:
 *	Interchange
 *	Multiply and Add
 *	Scale
 *	Reduced Row Echelon Form
 */
class Matrix {
	LinkedList<LinkedList<Fraction>> matrix;
	int numRows;
	int numCols;

	static class Coordinate {
		int row;
		int col;

		Coordinate(int r, int c) {
			row = r;
			col = c;
		}

		public String toString() {
			return "(" + row + ", " + col + ")";
		}
	}

	Matrix(double [][] m) {
		numRows = m.length;
		numCols = m[0].length;

		matrix = new LinkedList<LinkedList<Fraction>>();

		for (int i = 0; i < numRows; i++) {
			matrix.add(new LinkedList<Fraction>());
			for (int j = 0; j < numCols; j++) {
				try {
					matrix.get(i).add(new Fraction(m[i][j]));
				} catch (FractionConversionException e) {
					System.err.println("Fraction could not be converted from double by apache commons . . .");
				}
			}
		}
	}

	public void Interchange(Coordinate a, Coordinate b) {
		LinkedList<Fraction> temp = matrix.get(a.row);
		matrix.set(a.row, matrix.get(b.row));
		matrix.set(b.row, temp);

		int t = a.row;
		a.row = b.row;
		b.row = t;
	}

	public void Scale(Coordinate x, Fraction d) {
		LinkedList<Fraction> row = matrix.get(x.row);
		for (int i = 0; i < numCols; i++) {
			row.set(i, row.get(i).multiply(d));
		}
	}

	public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) {
		LinkedList<Fraction> row = matrix.get(to.row);
		LinkedList<Fraction> rowMultiplied = matrix.get(from.row);

		for (int i = 0; i < numCols; i++) {
			row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar))));
		}
	}

	public void RREF() {
		Coordinate pivot = new Coordinate(0,0);

		int submatrix = 0;
		for (int x = 0; x < numCols; x++) {
			pivot = new Coordinate(pivot.row, x);
			//Step 1
				//Begin with the leftmost nonzero column. This is a pivot column. The pivot position is at the top.
				for (int i = x; i < numCols; i++) {
					if (isColumnZeroes(pivot) == false) {
						break;
					} else {
						pivot.col = i;
					}
				}
			//Step 2
				//Select a nonzero entry in the pivot column with the highest absolute value as a pivot.
				pivot = findPivot(pivot);

				if (getCoordinate(pivot).doubleValue() == 0.0) {
					pivot.row++;
					continue;
				}

				//If necessary, interchange rows to move this entry into the pivot position.
				//move this row to the top of the submatrix
				if (pivot.row != submatrix) {
					Interchange(new Coordinate(submatrix, pivot.col), pivot);
				}

				//Force pivot to be 1
				if (getCoordinate(pivot).doubleValue() != 1) {
					/*
					System.out.println(getCoordinate(pivot));
					System.out.println(pivot);
					System.out.println(matrix);
					*/
					Fraction scalar = getCoordinate(pivot).reciprocal();
					Scale(pivot, scalar);
				}
			//Step 3
				//Use row replacement operations to create zeroes in all positions below the pivot.
				//belowPivot = belowPivot + (Pivot * -belowPivot)
				for (int i = pivot.row; i < numRows; i++) {
					if (i == pivot.row) {
						continue;
					}
					Coordinate belowPivot = new Coordinate(i, pivot.col);
					Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot)));
					MultiplyAndAdd(belowPivot, pivot, complement);
				}
			//Step 5
				//Beginning with the rightmost pivot and working upward and to the left, create zeroes above each pivot.
				//If a pivot is not 1, make it 1 by a scaling operation.
					//Use row replacement operations to create zeroes in all positions above the pivot
				for (int i = pivot.row; i >= 0; i--) {
					if (i == pivot.row) {
						if (getCoordinate(pivot).doubleValue() != 1.0) {
							Scale(pivot, getCoordinate(pivot).reciprocal());
						}
						continue;
					}
					if (i == pivot.row) {
						continue;
					}

					Coordinate abovePivot = new Coordinate(i, pivot.col);
					Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot)));
					MultiplyAndAdd(abovePivot, pivot, complement);
				}
			//Step 4
				//Ignore the row containing the pivot position and cover all rows, if any, above it.
				//Apply steps 1-3 to the remaining submatrix. Repeat until there are no more nonzero entries.
				if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) {
					break;
				}

				submatrix++;
				pivot.row++;
		}
	}

	public boolean isColumnZeroes(Coordinate a) {
		for (int i = 0; i < numRows; i++) {
			if (matrix.get(i).get(a.col).doubleValue() != 0.0) {
				return false;
			}
		}

		return true;
	}

	public boolean isRowZeroes(Coordinate a) {
		for (int i = 0; i < numCols; i++) {
			if (matrix.get(a.row).get(i).doubleValue() != 0.0) {
				return false;
			}
		}

		return true;
	}

	public Coordinate findPivot(Coordinate a) {
		int first_row = a.row;
		Coordinate pivot = new Coordinate(a.row, a.col);
		Coordinate current = new Coordinate(a.row, a.col);

		for (int i = a.row; i < (numRows - first_row); i++) {
			current.row = i;
			if (getCoordinate(current).doubleValue() == 1.0) {
				Interchange(current, a);
			}
		}

		current.row = a.row;
		for (int i = current.row; i < (numRows - first_row); i++) {
			current.row = i;
			if (getCoordinate(current).doubleValue() != 0) {
				pivot.row = i;
				break;
			}
		}

		return pivot;
	}

	public Fraction getCoordinate(Coordinate a) {
		return matrix.get(a.row).get(a.col);
	}

	public String toString() {
		return matrix.toString().replace("], ", "]\n");
	}

	public static void main (String[] args) {
        	double[][] matrix_1 = {
			{1, 2, -1, -4},
			{2, 3, -1, -11},
			{-2, 0, -3, 22}
		};

		Matrix x = new Matrix(matrix_1);
		System.out.println("before\n" + x.toString() + "\n");
		x.RREF();
		System.out.println("after\n" + x.toString() + "\n");

		double matrix_2 [][] = {
			{2, 0, -1, 0, 0},
			{1, 0, 0, -1, 0},
			{3, 0, 0, -2, -1},
			{0, 1, 0, 0, -2},
			{0, 1, -1, 0, 0}
		};

		Matrix y = new Matrix(matrix_2);
		System.out.println("before\n" + y.toString() + "\n");
		y.RREF();
		System.out.println("after\n" + y.toString() + "\n");

		double matrix_3 [][] = {
			{1, 2, 3, 4, 3, 1},
			{2, 4, 6, 2, 6, 2},
			{3, 6, 18, 9, 9, -6},
			{4, 8, 12, 10, 12, 4},
			{5, 10, 24, 11, 15, -4}
		};

		Matrix z = new Matrix(matrix_3);
		System.out.println("before\n" + z.toString() + "\n");
		z.RREF();
		System.out.println("after\n" + z.toString() + "\n");

		double matrix_4 [][] = {
			{0, 1},
			{1, 2},
			{0,5}
		};

		Matrix a = new Matrix(matrix_4);
		System.out.println("before\n" + a.toString() + "\n");
		a.RREF();
		System.out.println("after\n" + a.toString() + "\n");
	}
}


package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
)

func main() {
	if line, err := rsl("input.txt", 7); err == nil {
		fmt.Println("7th line:")
		fmt.Println(line)
	} else {
		fmt.Println("rsl:", err)
	}
}

func rsl(fn string, n int) (string, error) {
	if n < 1 {
		return "", fmt.Errorf("invalid request: line %d", n)
	}
	f, err := os.Open(fn)
	if err != nil {
		return "", err
	}
	defer f.Close()
	bf := bufio.NewReader(f)
	var line string
	for lnum := 0; lnum < n; lnum++ {
		line, err = bf.ReadString('\n')
		if err == io.EOF {
			switch lnum {
			case 0:
				return "", errors.New("no lines in file")
			case 1:
				return "", errors.New("only 1 line")
			default:
				return "", fmt.Errorf("only %d lines", lnum)
			}
		}
		if err != nil {
			return "", err
		}
	}
	if line == "" {
		return "", fmt.Errorf("line %d empty", n)
	}
	return line, nil
}


def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
    if (lineNumber == 7) {
        line = currentLine
    }
}
println "Line 7 = $line"


// modifies the matrix in-place
Matrix.prototype.toReducedRowEchelonForm = function() {
    var lead = 0;
    for (var r = 0; r < this.rows(); r++) {
        if (this.columns() <= lead) {
            return;
        }
        var i = r;
        while (this.mtx[i][lead] == 0) {
            i++;
            if (this.rows() == i) {
                i = r;
                lead++;
                if (this.columns() == lead) {
                    return;
                }
            }
        }

        var tmp = this.mtx[i];
        this.mtx[i] = this.mtx[r];
        this.mtx[r] = tmp;

        var val = this.mtx[r][lead];
        for (var j = 0; j < this.columns(); j++) {
            this.mtx[r][j] /= val;
        }

        for (var i = 0; i < this.rows(); i++) {
            if (i == r) continue;
            val = this.mtx[i][lead];
            for (var j = 0; j < this.columns(); j++) {
                this.mtx[i][j] -= val * this.mtx[r][j];
            }
        }
        lead++;
    }
    return this;
}

var m = new Matrix([
  [ 1, 2, -1, -4],
  [ 2, 3, -1,-11],
  [-2, 0, -3, 22]
]);
print(m.toReducedRowEchelonForm());
print();

m = new Matrix([
  [ 1, 2, 3, 7],
  [-4, 7,-2, 7],
  [ 3, 3, 0, 7]
]);
print(m.toReducedRowEchelonForm());


main :: IO ()
main = do contents <- readFile filename
          case drop 6 $ lines contents of
            []  -> error "File has less than seven lines"
            l:_ -> putStrLn l
  where filename = "testfile"


procedure main()
write(readline("foo.bar.txt",7)|"failed")
end

procedure readline(f,n)                         # return n'th line of file f
f := open(\f,"r") | fail                        # open file
every  i := n & line := |read(f) \ n do i -:= 1  #  <== here
close(f)
if i = 0 then return line
end


// version 1.1.51

typealias Matrix = Array<DoubleArray>

/* changes the matrix to RREF 'in place' */
fun Matrix.toReducedRowEchelonForm() {
    var lead = 0
    val rowCount = this.size
    val colCount = this[0].size
    for (r in 0 until rowCount) {
        if (colCount <= lead) return
        var i = r

        while (this[i][lead] == 0.0) {
            i++
            if (rowCount == i) {
                i = r
                lead++
                if (colCount == lead) return
            }
        }

        val temp = this[i]
        this[i] = this[r]
        this[r] = temp

        if (this[r][lead] != 0.0) {
           val div = this[r][lead]
           for (j in 0 until colCount) this[r][j] /= div
        }

        for (k in 0 until rowCount) {
            if (k != r) {
                val mult = this[k][lead]
                for (j in 0 until colCount) this[k][j] -= this[r][j] * mult
            }
        }

        lead++
    }
}

fun Matrix.printf(title: String) {
    println(title)
    val rowCount = this.size
    val colCount = this[0].size

    for (r in 0 until rowCount) {
        for (c in 0 until colCount) {
            if (this[r][c] == -0.0) this[r][c] = 0.0  // get rid of negative zeros
            print("${"% 6.2f".format(this[r][c])}  ")
        }
        println()
    }

    println()
}

fun main(args: Array<String>) {
    val matrices = listOf(
        arrayOf(
            doubleArrayOf( 1.0, 2.0, -1.0, -4.0),
            doubleArrayOf( 2.0, 3.0, -1.0, -11.0),
            doubleArrayOf(-2.0, 0.0, -3.0,  22.0)
        ),
        arrayOf(
            doubleArrayOf(1.0,  2.0,  3.0,  4.0,  3.0,  1.0),
            doubleArrayOf(2.0,  4.0,  6.0,  2.0,  6.0,  2.0),
            doubleArrayOf(3.0,  6.0, 18.0,  9.0,  9.0, -6.0),
            doubleArrayOf(4.0,  8.0, 12.0, 10.0, 12.0,  4.0),
            doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0)
        )
    )

    for (m in matrices) {
        m.printf("Original matrix:")
        m.toReducedRowEchelonForm()
        m.printf("Reduced row echelon form:")
    }
}


package linenbr7;

import java.io.*;

public class LineNbr7 {

    public static void main(String[] args) throws Exception {
        File f = new File(args[0]);
        if (!f.isFile() || !f.canRead())
            throw new IOException("can't read " + args[0]);

        BufferedReader br = new BufferedReader(new FileReader(f));
        try (LineNumberReader lnr = new LineNumberReader(br)) {
            String line = null;
            int lnum = 0;
            while ((line = lnr.readLine()) != null
                    && (lnum = lnr.getLineNumber()) < 7) {
            }

            switch (lnum) {
                case 0:
                    System.out.println("the file has zero length");
                    break;
                case 7:
                    boolean empty = "".equals(line);
                    System.out.println("line 7: " + (empty ? "empty" : line));
                    break;
                default:
                    System.out.println("the file has only " + lnum + " line(s)");
            }
        }
    }
}


# Input - a line number to read, counting from 1
# Output - a stream with 0 or 1 items
def read_line:
  . as $in
  | label $top
  | foreach inputs as $line
      (0; .+1; if . == $in then $line, break $top else empty end) ;


function ToReducedRowEchelonForm ( M )
    local lead = 1
    local n_rows, n_cols = #M, #M[1]

    for r = 1, n_rows do
        if n_cols <= lead then break end

        local i = r
        while M[i][lead] == 0 do
            i = i + 1
            if n_rows == i then
                i = r
                lead = lead + 1
                if n_cols == lead then break end
            end
        end
        M[i], M[r] = M[r], M[i]

        local m = M[r][lead]
        for k = 1, n_cols do
            M[r][k] = M[r][k] / m
        end
        for i = 1, n_rows do
            if i ~= r then
                local m = M[i][lead]
                for k = 1, n_cols do
                    M[i][k] = M[i][k] - m * M[r][k]
                end
            end
        end
        lead = lead + 1
    end
end

M = { { 1, 2, -1, -4 },
      { 2, 3, -1, -11 },
      { -2, 0, -3, 22 } }

res = ToReducedRowEchelonForm( M )

for i = 1, #M do
    for j = 1, #M[1] do
        io.write( M[i][j], "  " )
    end
    io.write( "\n" )
end


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    /* The following code reads the whole file into memory
       and so should not be used for large files
       which should instead be read line by line until the
       desired line is reached */

    val lines = File("input.txt").readLines()
    if (lines.size < 7)
        println("There are only ${lines.size} lines in the file")
    else {
        val line7 = lines[6].trim()
        if (line7.isEmpty())
            println("The seventh line is empty")
        else
            println("The seventh line is : $line7")
    }
}

/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/


local(f) = file('unixdict.txt')
handle => { #f->close }
local(this_line = string,line = 0)
#f->forEachLine => {
	#line++
	#line == 7 ? #this_line = #1
	#line == 7 ? loop_abort
}
#this_line // 6th, which is the 7th line in the file


Module Base1 {
      dim base 1, A(3, 4)
      A(1, 1)= 1,    2,   -1,   -4,  2 ,   3,   -1,   -11,  -2  ,  0 ,  -3,    22
      lead=1
      rowcount=3
      columncount=4
      gosub disp()
      for r=1 to rowcount {
            if columncount<lead then exit
            i=r
            while A(i,lead)=0 {
                  i++
                  if rowcount=i then i=r : lead++ : if columncount<lead then exit
            }
            for c =1 to columncount {
                  swap A(i, c), A(r, c)
            }
              if A(r, lead)<>0 then {
                  div1=A(r,lead)
                  For c =1 to columncount {
                      A( r, c)/=div1
                  }
            }
            for i=1 to rowcount {
                  if i<>r then {
                        mult=A(i,lead)
                        for j=1 to columncount {
                                 A(i,j)-=A(r,j)*mult
                        }
                  }
            }
            lead=lead+1
      }
      disp()
      sub disp()
            local i, j
            for i=1 to rowcount
                  for j=1 to columncount
                        Print A(i, j),
                  Next j
                  if pos>0 then print
            Next i
      End sub
}
Base1


fileName$    ="F:\sample.txt"
requiredLine =7

open fileName$ for input as #i
    f$ =input$( #i, lof( #i))
close #i

line7$ =word$( f$, 7, chr$( 13))
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."

print line7$


function fileLine (lineNum, fileName)
  local count = 0
  for line in io.lines(fileName) do
    count = count + 1
    if count == lineNum then return line end
  end
  error(fileName .. " has fewer than " .. lineNum .. " lines.")
end

print(fileLine(7, "test.txt"))


path := "file.txt":
specificLine := proc(path, num)
	local i, input:
	for i to num do
		input := readline(path):
		if input = 0 then break; end if:
	end do:
	if i = num+1 then printf("Line %d, %s", num, input):
	elif i <= num then printf ("Line number %d is not reached",num): end if:
end proc:


import rationals, strutils

type Fraction = Rational[int]

const Zero: Fraction = 0 // 1

type Matrix[M, N: static Positive] = array[M, array[N, Fraction]]

func toMatrix[M, N: static Positive](a: array[M, array[N, int]]): Matrix[M, N] =
  ## Convert a matrix of integers to a matrix of integer fractions.

  for i in 0..<M:
    for j in 0..<N:
      result[i][j] = a[i][j] // 1

func transformToRref(mat: var Matrix) =
  ## Transform the given matrix to reduced row echelon form.

  var lead = 0

  for r in 0..<mat.M:

    if lead >= mat.N: return

    var i = r
    while mat[i][lead] == Zero:
      inc i
      if i == mat.M:
        i = r
        inc lead
        if lead == mat.N: return
    swap mat[i], mat[r]

    if (let d = mat[r][lead]; d) != Zero:
      for item in mat[r].mitems:
        item /= d

    for i in 0..<mat.M:
      if i != r:
        let m = mat[i][lead]
        for c in 0..<mat.N:
          mat[i][c] -= mat[r][c] * m

    inc lead

proc `$`(mat: Matrix): string =
  ## Display a matrix.

  for row in mat:
    var line = ""
    for val in row:
      line.addSep(" ", 0)
      line.add val.toFloat.formatFloat(ffDecimal, 2).align(7)
    echo line

#———————————————————————————————————————————————————————————————————————————————————————————————————

template runTest(mat: Matrix) =
  ## Run a test using matrix "mat".

  echo "Original matrix:"
  echo mat
  echo "Reduced row echelon form:"
  mat.transformToRref()
  echo mat
  echo ""

var m1 = [[ 1, 2, -1,  -4],
          [ 2, 3, -1, -11],
          [-2, 0, -3,  22]].toMatrix()

var m2 = [[2, 0, -1,  0,  0],
          [1, 0,  0, -1,  0],
          [3, 0,  0, -2, -1],
          [0, 1,  0,  0, -2],
          [0, 1, -1,  0,  0]].toMatrix()

var m3 = [[1,  2,  3,  4,  3,  1],
          [2,  4,  6,  2,  6,  2],
          [3,  6, 18,  9,  9, -6],
          [4,  8, 12, 10, 12,  4],
          [5, 10, 24, 11, 15, -4]].toMatrix()

var m4 = [[0, 1],
          [1, 2],
          [0, 5]].toMatrix()

runTest(m1)
runTest(m2)
runTest(m3)
runTest(m4)


If[# != EndOfFile , Print[#]]& @ ReadList["file",  String, 7]


  eln = 7;  % extract line number 7
  line = '';
  fid = fopen('foobar.txt','r');
  if (fid < 0)
	printf('Error:could not open file\n')
  else
        n = 0;
	while ~feof(fid),
              n = n + 1;
              if (n ~= eln),
                    fgetl(fid);
              else
                    line = fgetl(fid);
              end
	end;
        fclose(fid);
  end;
  printf('line %i: %s\n',eln,line);


iter = io.lines 'test.txt'
for i=0, 5
  error 'Not 7 lines in file' if not iter!

print iter!


def getline(fname, linenum)
	contents = null
	try
		contents = new(Nanoquery.IO.File).read()
		return contents[linenum]
	catch
		if contents = null
			throw new(Exception, "unable to read from file '" + fname + "'")
		else
			throw new(Exception, "unable to retrieve line " + linenum + " from file: not enough lines")
		end
	end
end


class RowEchelon {
  function : Main(args : String[]) ~ Nil {
    matrix := [
      [1, 2, -1,  -4 ]
      [2, 3, -1, -11 ]
      [-2, 0, -3,  22]
    ];

    matrix := Rref(matrix);

    sizes := matrix->Size();
    for(i := 0; i < sizes[0]; i += 1;) {
      for(j := 0; j < sizes[1]; j += 1;) {
        IO.Console->Print(matrix[i,j])->Print(",");
      };
      IO.Console->PrintLine();
    };
  }

  function : native : Rref(matrix : Int[,]) ~ Int[,] {
    lead := 0;
    sizes := matrix->Size();
    rowCount := sizes[0];
    columnCount := sizes[1];

    for(r := 0; r < rowCount; r+=1;) {
      if (columnCount <= lead) {
        break;
      };

      i := r;
      while(matrix[i, lead] = 0) {
        i+=1;
        if (i = rowCount) {
          i := r;
          lead += 1;
          if (columnCount = lead) {
            lead-=1;
            break;
           };
        };
      };

      for (j := 0; j < columnCount; j+=1;) {
        temp := matrix[r, j];
        matrix[r, j] := matrix[i, j];
        matrix[i, j] := temp;
      };

      div := matrix[r, lead];
      for(j := 0; j < columnCount; j+=1;) {
        matrix[r, j] /= div;
      };

      for(j := 0; j < rowCount; j+=1;) {
        if (j <> r) {
          sub := matrix[j, lead];
          for (k := 0; k < columnCount; k+=1;) {
            matrix[j, k] -= sub * matrix[r, k];
          };
         };
      };
      lead+=1;
    };

    return matrix;
  }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

parse arg inFileName lineNr .

if inFileName = '' | inFileName = '.' then inFileName = './data/input.txt'
if lineNr     = '' | lineNr     = '.' then lineNr     = 7

do
  lineTxt = readLine(inFileName, lineNr)
  say '<textline number="'lineNr.right(5, 0)'">'lineTxt'</textline>'
catch ex = Exception
  ex.printStackTrace()
end

return

-- =============================================================================
-- NetRexx/Java programs don't have a special mechanism to seek to a specified line number
-- the simple solution is to iterate through file. (Costly for very large files)
method readLine(inFileName, lineNr) public static signals IOException, FileNotFoundException

  lineReader = LineNumberReader(FileReader(File(inFileName)))
  notFound   = isTrue
  lineTxt    = ''
  loop label reading forever
    line = lineReader.readLine()
    select
      when lineReader.getLineNumber() = lineNr then do
        lineTxt  = line
        notFound = isFalse
        leave reading -- terminate I/O loop
        end
      when line = null then do
        leave reading -- terminate I/O loop
        end
      otherwise nop
      end
    finally
      lineReader.close()
    end reading

  if notFound then signal RuntimeException('File' inFileName 'does not contain line' lineNr.right(5))

  return lineTxt

-- =============================================================================
method isTrue() public static returns boolean
  return 1 == 1
-- =============================================================================
method isFalse() public static returns boolean
  return \(1 == 1)


import strformat

proc readLine(f: File; num: Positive): string =
  for n in 1..num:
    try:
      result = f.readLine()
    except EOFError:
      raise newException(IOError, &"Not enough lines in file; expected {num}, found {n - 1}.")

let f = open("test.txt", fmRead)
echo f.readLine(7)
f.close()


let input_line_opt ic =
  try Some (input_line ic)
  with End_of_file -> None

let nth_line n filename =
  let ic = open_in filename in
  let rec aux i =
    match input_line_opt ic with
    | Some line ->
        if i = n then begin
          close_in ic;
          (line)
        end else aux (succ i)
    | None ->
        close_in ic;
        failwith "end of file reached"
  in
  aux 1

let () =
  print_endline (nth_line 7 Sys.argv.(1))


let swap_rows m i j =
  let tmp = m.(i) in
  m.(i) <- m.(j);
  m.(j) <- tmp;
;;

let rref m =
  try
    let lead = ref 0
    and rows = Array.length m
    and cols = Array.length m.(0) in
    for r = 0 to pred rows do
      if cols <= !lead then
        raise Exit;
      let i = ref r in
      while m.(!i).(!lead) = 0 do
        incr i;
        if rows = !i then begin
          i := r;
          incr lead;
          if cols = !lead then
            raise Exit;
        end
      done;
      swap_rows m !i r;
      let lv = m.(r).(!lead) in
      m.(r) <- Array.map (fun v -> v / lv) m.(r);
      for i = 0 to pred rows do
        if i <> r then
          let lv = m.(i).(!lead) in
          m.(i) <- Array.mapi (fun i iv -> iv - lv * m.(r).(i)) m.(i);
      done;
      incr lead;
    done
  with Exit -> ()
;;

let () =
  let m =
    [| [|  1; 2; -1;  -4 |];
       [|  2; 3; -1; -11 |];
       [| -2; 0; -3;  22 |]; |]
  in
  rref m;

  Array.iter (fun row ->
    Array.iter (fun v ->
      Printf.printf " %d" v
    ) row;
    print_newline()
  ) m


Program FileTruncate;

uses
  SysUtils;

const
  filename = 'test';
  position = 7;

var
  myfile: text;
  line: string;
  counter: integer;

begin
  if not FileExists(filename) then
  begin
    writeln('Error: File does not exist.');
    exit;
  end;

  Assign(myfile, filename);
  Reset(myfile);
  counter := 0;
  Repeat
    if eof(myfile) then
    begin
      writeln('Error: The file "', filename, '" is too short. Cannot read line ', position);
      Close(myfile);
      exit;
    end;
    inc(counter);
    readln(myfile);
  until counter = position - 1;
  readln(myfile, line);
  Close(myfile);
  writeln(line);
end.


matrref(M)=
{
	my(s=matsize(M),t=s[1]);
	for(i=1,s[2],
		if(M[t,i]==0, next);
		M[t,] /= M[t,i];
		for(j=1,t-1,
			M[j,] -= M[j,i]*M[t,]
		);
		for(j=t+1,s[1],
			M[j,] -= M[j,i]*M[t,]
		);
		if(t--<1,break)
	);
	M;
}
addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");


#!/usr/bin/perl -s
# invoke as <scriptname> -n=7 [input]
while (<>) { $. == $n and print, exit }
die "file too short\n";


object lines = get_text("TEST.TXT",GT_LF_STRIPPED)
if sequence(lines) and length(lines)>=7 then
    ?lines[7]
else
    ?"no line 7"
end if


include ..\Utilitys.pmt

argument 1 get "r" fopen var f drop
0
7 for
    f fgets number? if f fclose exitfor else nip nip endif
endfor
print   /# show -1 if past eof #/


<?php
  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];

  function fileLine ($lineNum, $file) {
    $count = 0;
    while (!feof($file)) {
      $count++;
      $line = fgets($file);
      if ($count == $lineNum) return $line;
    }
    die("Requested file has fewer than ".$lineNum." lines!");
  }

  @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
  if (!$fp) die("Input file not found!");
  echo fileLine(7, $fp);
?>


(in "file.txt"
   (do 6 (line))
   (or (line) (quit "No 7 lines")) )


declare text character (1000) varying, line_no fixed;

get (line_no);
on endfile (f) begin;
  put skip list ('the specified line does not exist');
  go to next;
end;

get file (f) edit ((text do i = 1 to line_no)) (L);

put skip list (text);
next: ;


100H: /* READ A SPECIFIC LINE FROM A FILE                                    */

   DECLARE FALSE    LITERALLY '0', TRUE LITERALLY '0FFH';
   DECLARE NL$CHAR  LITERALLY '0AH';                     /* NEWLINE: CHAR 10 */
   DECLARE EOF$CHAR LITERALLY '26';                      /* EOF: CTRL-Z      */
   /* CP/M BDOS SYSTEM CALL, RETURNS A VALUE                                 */
   BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   /* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
   BDOS$P: PROCEDURE( FN, ARG );   DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   EXIT:      PROCEDURE; CALL BDOS$P( 0, 0 ); END;      /* CP/M SYSTEM RESET */
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS$P( 2, C );    END;
   PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S );    END;
   PR$NL:     PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) );       END;
   PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH  */
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
      V = N;
      W = LAST( N$STR );
      N$STR( W ) = '$';
      N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PR$STRING( .N$STR( W ) );
   END PR$NUMBER;
   FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
      DECLARE FCB ADDRESS;          /*                 FCB EXISTS            */
      RETURN ( BDOS( 17, FCB ) < 4 );
   END FL$EXISTS ;
   FL$OPEN:   PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB  */
      DECLARE FCB ADDRESS;
      RETURN ( BDOS( 15, FCB ) < 4 );
   END FL$OPEN;
   FL$READ:   PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB         */
      DECLARE FCB ADDRESS;
      RETURN ( BDOS( 20, FCB ) = 0 );
   END FL$READ;
   FL$CLOSE:  PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */
      DECLARE FCB ADDRESS;
      RETURN ( BDOS( 16, FCB ) < 4 );
   END FL$CLOSE;

   PR$BYTE:   PROCEDURE( B );       /* PRINT B EITHER AS A CHAR OR IN HEX    */
      DECLARE B BYTE;
      PR$HEX: PROCEDURE( H );       /* PRINT A HEX DIGIT                     */
         DECLARE H BYTE;
         IF H < 10 THEN CALL PR$CHAR(   H        + '0' );
         ELSE           CALL PR$CHAR( ( H - 10 ) + 'A' );
      END PR$HEX;
      IF B >= ' ' AND B < 7FH AND B <> '$' THEN DO;
         /* PRINTABLE CHAR AND NOT A $, SHOW AS A CHARACTER                  */
         CALL PR$CHAR( B );
         END;
      ELSE DO;
         /* NON-PRINTING CHAR OR $ - SHOW IN HEX                             */
         CALL PR$CHAR( '$' );
         CALL PR$HEX( SHR( B, 4 ) );
         CALL PR$HEX( B AND 0FH );
      END;
   END PR$BYTE;

   /* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC.  */
   /* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */
   /* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2          */
   /* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END  */
   /* OF FCB2, SO WE NEED TO GET THE LINE NUMBER FROM FCB2 FIRST             */

   DECLARE FCB$SIZE      LITERALLY '36';  /* SIZE OF A FCB                   */
   DECLARE FCB1          LITERALLY '5CH'; /* ADDRESS OF FIRST  FCB           */
   DECLARE FCB2          LITERALLY '6CH'; /* ADDRESS OF SECOND FCB           */
   DECLARE DMA$BUFFER    LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS      */
   DECLARE DMA$SIZE      LITERALLY '128'; /* SIZE OF THE DMA BUFFER          */

   DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE;

   /* GET THE LINE NUMBER FROM THE SECOND PARAMETER                          */
   DECLARE LINE$NUMBER ADDRESS;
   LINE$NUMBER = 0;
   DO F$PTR = FCB2 + 1 TO FCB2 + 8;
      IF F$CHAR >= '0' AND F$CHAR <= '9' THEN DO;
         LINE$NUMBER = ( LINE$NUMBER * 10 ) + ( F$CHAR - '0' );
      END;
   END;
   /* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2                              */
   DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 );
      F$CHAR = 0;
   END;

   /* SHOW THE REQUIRED LINE FROM THE FILE, IF THE FILE AND LINE EXIST       */
   IF NOT FL$EXISTS( FCB1 ) THEN DO;    /* THE FILE DOES NOT EXIST           */
      CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL;
      END;
   ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE           */
      CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL;
      END;
   ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO FIND THE LINE          */
      DECLARE LN ADDRESS, GOT$RCD BYTE, GOT$LINE BYTE, DMA$END ADDRESS;
      DMA$END  = DMA$BUFFER + ( DMA$SIZE - 1 );
      GOT$RCD  = FL$READ( FCB1 ); /* GET THE FIRST RECORD                    */
      GOT$LINE = FALSE;
      F$PTR    = DMA$BUFFER;
      LN       = 1;
      CALL PR$NUMBER( LINE$NUMBER ); CALL PR$STRING( .': <$' );
      DO WHILE( GOT$RCD AND LN <= LINE$NUMBER );
         IF F$PTR > DMA$END THEN DO;
            /* AT THE END OF THE BUFFER - GET THE NEXT RECORD                */
            GOT$RCD = FL$READ( FCB1 );
            F$PTR   = DMA$BUFFER;
            END;
         ELSE IF F$CHAR = NL$CHAR     THEN DO;                /* END OF LINE */
            LN = LN + 1;
            IF LN = LINE$NUMBER       THEN GOT$LINE = TRUE;
            END;
         ELSE IF F$CHAR = EOF$CHAR    THEN GOT$RCD  = FALSE;  /* END OF FILE */
         ELSE IF LN     = LINE$NUMBER THEN CALL PR$BYTE( F$CHAR );
         F$PTR = F$PTR + 1;
      END;
      CALL PR$CHAR( '>' ); CALL PR$NL;
      /* SHOULD NOW HAVE EOF OR THE END OF THE REQUIRED LINE                 */
      IF NOT GOT$LINE THEN DO;
         /* COULDN'T READ THE SPECIFIED LINE                                 */
         CALL PR$STRING( .'CANNOT READ LINE $' );
         CALL PR$NUMBER( LINE$NUMBER );
      END;
      /* CLOSE THE FILE                                                      */
      IF NOT FL$CLOSE( FCB1 ) THEN DO;
         CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL;
      END;
   END;

   CALL EXIT;

EOF


with javascript_semantics
function ToReducedRowEchelonForm(sequence M)
integer lead = 1,
        rowCount = length(M),
        columnCount = length(M[1]),
        i
    for r=1 to rowCount do
        if lead>=columnCount then exit end if
        i = r
        while M[i][lead]=0 do
            i += 1
            if i=rowCount then
                i = r
                lead += 1
                if lead=columnCount then exit end if
            end if
        end while
        object mr = sq_div(M[i],M[i][lead])
        M[i] = M[r]
        M[r] = mr
        for j=1 to rowCount do
            if j!=r then
                M[j] = sq_sub(M[j],sq_mul(M[j][lead],M[r]))
            end if
        end for
        lead += 1
    end for
    return M
end function

? ToReducedRowEchelonForm(
    { { 1, 2, -1, -4 },
      { 2, 3, -1, -11 },
      { -2, 0, -3, 22 } })


$file = Get-Content c:\file.txt
if ($file.count -lt 7)
{Write-Warning "The file is too short!"}
else
{
    $file | Where Readcount -eq 7 | set-variable -name Line7
}


Structure lineLastRead
  lineRead.i
  line.s
EndStructure

Procedure readNthLine(file, n, *results.lineLastRead)
  *results\lineRead = 0
  While *results\lineRead < n And Not Eof(file)
    *results\line = ReadString(file)
    *results\lineRead + 1
  Wend

  If *results\lineRead = n
    ProcedureReturn 1
  EndIf
EndProcedure

Define filename.s = OpenFileRequester("Choose file to read a line from", "*.*", "All files (*.*)|*.*", 0)
If filename
  Define file = ReadFile(#PB_Any, filename)
  If file
    Define fileReadResults.lineLastRead, lineToRead = 7
    If readNthLine(file, lineToRead, fileReadResults)
      MessageRequester("Results", fileReadResults\line)
    Else
      MessageRequester("Error", "There are less than " + Str(lineToRead) + " lines in file.")
    EndIf
    CloseFile(file)
  Else
    MessageRequester("Error", "Couldn't open file " + filename + ".")
  EndIf
EndIf


<?php

function rref($matrix)
{
    $lead = 0;
    $rowCount = count($matrix);
    if ($rowCount == 0)
        return $matrix;
    $columnCount = 0;
    if (isset($matrix[0])) {
        $columnCount = count($matrix[0]);
    }
    for ($r = 0; $r < $rowCount; $r++) {
        if ($lead >= $columnCount)
            break;        {
            $i = $r;
            while ($matrix[$i][$lead] == 0) {
                $i++;
                if ($i == $rowCount) {
                    $i = $r;
                    $lead++;
                    if ($lead == $columnCount)
                        return $matrix;
                }
            }
            $temp = $matrix[$r];
            $matrix[$r] = $matrix[$i];
            $matrix[$i] = $temp;
        }        {
            $lv = $matrix[$r][$lead];
            for ($j = 0; $j < $columnCount; $j++) {
                $matrix[$r][$j] = $matrix[$r][$j] / $lv;
            }
        }
        for ($i = 0; $i < $rowCount; $i++) {
            if ($i != $r) {
                $lv = $matrix[$i][$lead];
                for ($j = 0; $j < $columnCount; $j++) {
                    $matrix[$i][$j] -= $lv * $matrix[$r][$j];
                }
            }
        }
        $lead++;
    }
    return $matrix;
}
?>


with open('xxx.txt') as f:
    for i, line in enumerate(f):
        if i == 6:
            break
    else:
        print('Not 7 lines in file')
        line = None


> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item


#lang racket

;; simple, but reads the whole file
(define s1 (list-ref (file->lines "some-file") 6))

;; more efficient: read and discard n-1 lines
(define s2
  (call-with-input-file "some-file"
    (λ(i) (for/last ([line (in-lines i)] [n 7]) line))))


(de reducedRowEchelonForm (Mat)
   (let (Lead 1  Cols (length (car Mat)))
      (for (X Mat X (cdr X))
         (NIL
            (loop
               (T (seek '((R) (n0 (get R 1 Lead))) X)
                  @ )
               (T (> (inc 'Lead) Cols)) ) )
         (xchg @ X)
         (let D (get X 1 Lead)
            (map
               '((R) (set R (/ (car R) D)))
               (car X) ) )
         (for Y Mat
            (unless (== Y (car X))
               (let N (- (get Y Lead))
                  (map
                     '((Dst Src)
                        (inc Dst (* N (car Src))) )
                     Y
                     (car X) ) ) ) )
         (T (> (inc 'Lead) Cols)) ) )
   Mat )


def ToReducedRowEchelonForm( M):
    if not M: return
    lead = 0
    rowCount = len(M)
    columnCount = len(M[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while M[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        M[i],M[r] = M[r],M[i]
        lv = M[r][lead]
        M[r] = [ mrx / float(lv) for mrx in M[r]]
        for i in range(rowCount):
            if i != r:
                lv = M[i][lead]
                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
        lead += 1

mtx = [
   [ 1, 2, -1, -4],
   [ 2, 3, -1, -11],
   [-2, 0, -3, 22],]

ToReducedRowEchelonForm( mtx )

for rw in mtx:
  print ', '.join( (str(rv) for rv in rw) )


x: pick read/lines request-file/only 7
either x [print x] [print "No seventh line"]


>> x: pick read/lines %file.txt 7

case [
    x = none  [print "File has less than seven lines"]
    (length? x) = 0 [print "Line 7 is empty"]
    (length? x) > 0 [print append "Line seven =  " x]
]


/*REXX program reads a specific line from a file  (and displays the length and content).*/
parse arg FID n .                                /*obtain optional arguments from the CL*/
if FID=='' | FID==","  then  FID= 'JUNK.TXT'     /*not specified?  Then use the default.*/
if   n=='' |   n==","  then    n=7               /* "      "         "   "   "      "   */

if lines(FID)==0  then  call ser "wasn't found." /*see if the file    exists  (or not). */

call linein FID, n-1                             /*read the record previous to  N.      */
if lines(FID)==0  then  call ser "doesn't contain"       N        'lines.'
                                                 /* [↑]  any more lines to read in file?*/

$=linein(FID)                                    /*read the   Nth  record in the file.  */

say 'File '  FID  " line "  N  ' has a length of: '         length($)
say 'File '  FID  " line "  N  'contents: '   $  /*display the contents of the Nth line.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser:   say;     say '***error!***  File '     FID     " "    arg(1);      say;     exit 13


fp = fopen("C:\Ring\ReadMe.txt","r")
n = 0

r = ""
while isstring(r)
      while n < 8
            r = fgetc(fp)
            if r = char(10) n++ see nl
            else see r ok
      end
end
fclose(fp)


rref <- function(m) {
  pivot <- 1
  norow <- nrow(m)
  nocolumn <- ncol(m)
  for(r in 1:norow) {
    if ( nocolumn <= pivot ) break;
    i <- r
    while( m[i,pivot] == 0 ) {
      i <- i + 1
      if ( norow == i ) {
        i <- r
        pivot <- pivot + 1
        if ( nocolumn == pivot ) return(m)
      }
    }
    trow <- m[i, ]
    m[i, ] <- m[r, ]
    m[r, ] <- trow
    m[r, ] <- m[r, ] / m[r, pivot]
    for(i in 1:norow) {
      if ( i != r )
        m[i, ] <- m[i, ] - m[r, ] * m[i, pivot]
    }
    pivot <- pivot + 1
  }
  return(m)
}

m <- matrix(c(1, 2, -1, -4,
              2, 3, -1, -11,
              -2, 0, -3, 22), 3, 4, byrow=TRUE)
print(m)
print(rref(m))


#lang racket
(require math)
(define (reduced-echelon M)
  (matrix-row-echelon M #t #t))

(reduced-echelon
 (matrix [[1 2 -1 -4]
          [2 3 -1 -11]
          [-2 0 -3 22]]))


fileName$    = "f:\sample.txt"
requiredLine = 7
open fileName$ for input as #f

for i = 1 to requiredLine
  if not(eof(#f)) then line input #f, a$
next i
close #f
print a$
end


use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;

fn main() {
    let path = Path::new("file.txt");
    let line_num = 7usize;
    let line = get_line_at(&path, line_num - 1);
    println!("{}", line.unwrap());
}

fn get_line_at(path: &Path, line_num: usize) -> Result<String, Error> {
    let file = File::open(path).expect("File not found or cannot be opened");
    let content = BufReader::new(&file);
    let mut lines = content.lines();
    lines.nth(line_num).expect("No line found at that position")
}


val lines = io.Source.fromFile("input.txt").getLines
val seventhLine = lines drop(6) next


$ include "seed7_05.s7i";

const func string: getLine (inout file: aFile, in var integer: lineNum) is func
  result
    var string: line is "";
  begin
    while lineNum > 1 and hasNext(aFile) do
      readln(aFile);
      decr(lineNum);
    end while;
    line := getln(aFile);
  end func;

const proc: main is func
  local
    var string: fileName is "input.txt";
    var file: aFile is STD_NULL;
    var string: line is "";
  begin
    aFile := open(fileName, "r");
    if aFile = STD_NULL then
      writeln("Cannot open " <& fileName);
    else
      line := getLine(aFile, 7);
      if eof(aFile) then
        writeln("The file does not have 7 lines");
      else
        writeln("The 7th line of the file is:");
        writeln(line);
      end if;
    end if;
  end func;


put line 7 of file "example.txt" into theLine


func getNthLine(filename, n) {
  var file = File.new(filename);
  file.open_r.each { |line|
    Num($.) == n && return line;
  }
  warn "file #{file} does not have #{n} lines, only #{$.}\n";
  return nil;
}

var line = getNthLine("/etc/passwd", 7);
print line if defined line;


/*REXX pgm performs Reduced Row Echelon Form (RREF), AKA row canonical form on a matrix)*/
cols= 0;  w= 0;   @. =0                          /*max cols in a row; max width; matrix.*/
mat.=;                  mat.1=  '    1   2   -1      -4   '
                        mat.2=  '    2   3   -1     -11   '
                        mat.3=  '   -2   0   -3      22   '
          do r=1  until mat.r=='';      _=mat.r  /*build  @.row.col  from (matrix) mat.X*/
                    do c=1  until _='';       parse  var   _    @.r.c  _
                    w= max(w, length(@.r.c) + 1) /*find the maximum width of an element.*/
                    end   /*c*/
          cols= max(cols, c)                     /*save the maximum number of columns.  */
          end   /*r*/
rows= r-1                                        /*adjust the row count (from DO loop). */
call showMat  'original matrix'                  /*display the original matrix──►screen.*/
!= 1                                             /*set the working column pointer to  1.*/
    /* ┌──────────────────────◄────────────────◄──── Reduced Row Echelon Form on matrix.*/
  do r=1  for rows  while cols>!                 /*begin to perform the heavy lifting.  */
  j= r                                           /*use a subsitute index for the DO loop*/
      do  while  @.j.!==0;    j= j + 1
      if j==rows  then do;    j= r;     != ! + 1;    if cols==!  then leave r;     end
      end      /*while*/
                                                 /* [↓]  swap rows J,R (but not if same)*/
      do _=1  for cols  while j\==r;    parse value   @.r._  @.j._    with    @.j._  @._._
      end      /*_*/
  ?= @.r.!
      do d=1  for cols  while ?\=1;     @.r.d= @.r.d / ?
      end      /*d*/                             /* [↑] divide row J by @.r.p ──unless≡1*/
          do k=1  for rows;             ?= @.k.! /*subtract (row K)   @.r.s  from row K.*/
          if k==r | ?=0  then iterate            /*skip  if  row K is the same as row R.*/
             do s=1  for cols;          @.k.s= @.k.s   -   ? * @.r.s
             end   /*s*/
          end      /*k*/                         /* [↑]  for the rest of numbers in row.*/
  != !+1                                         /*bump the working column pointer.     */
  end          /*r*/

call showMat  'matrix RREF'                      /*display the reduced row echelon form.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showMat: parse arg title;          say;  say center(title, 3 + (cols+1) * w, '─');    say
           do      r=1  for rows;   _=
                do c=1  for cols
                if @.r.c==''  then do;   say "***error*** matrix element isn't defined:"
                                         say 'row'    r",  column"    c'.';        exit 13
                                   end
                _= _  right(@.r.c, w)
                end   /*c*/
           say _                                 /*display a matrix row to the terminal.*/
           end        /*r*/;       return


line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.


lines = #.readlines("test.txt")
#.output("Seventh line of text:")
? #.size(lines,1)<7
  #.output("is absent")
!
  #.output(lines[7])
.


* Read rows 20 to 30 from somedata.dta
. use somedata in 20/30, clear

* Read rows for which the variable x is positive
. use somedata if x>0, clear


proc getNthLineFromFile {filename n} {
    set f [open $filename]
    while {[incr n -1] > 0} {
        if {[gets $f line] < 0} {
            close $f
            error "no such line"
        }
    }
    close $f
    return $line
}

puts [getNthLineFromFile example.txt 7]


# Project : Reduced row echelon form

matrix = [[1, 2, -1, -4],
              [2, 3, -1, -11],
              [ -2, 0, -3, 22]]
ref(matrix)
for row = 1 to 3
     for col = 1 to 4
           if matrix[row][col] = -0
              see "0 "
           else
              see "" + matrix[row][col] + " "
           ok
     next
     see nl
next

func ref(m)
nrows = 3
ncols = 4
lead = 1
for r = 1 to nrows
      if lead >= ncols
         exit
      ok
      i = r
      while m[i][lead] = 0
                i = i + 1
                if i = nrows
                   i = r
                   lead = lead + 1
                   if lead = ncols
                      exit 2
                   ok
                ok
      end
      for j = 1 to ncols
           temp = m[i][j]
           m[i][j] = m[r][j]
           m[r][j] = temp
      next
      n = m[r][lead]
      if n != 0
         for j = 1 to ncols
              m[r][j] = m[r][j] / n
         next
      ok
      for i = 1 to nrows
           if i != r
              n = m[i][lead]
              for j = 1 to ncols
                   m[i][j] = m[i][j] - m[r][j] * n
              next
           ok
      next
     lead = lead + 1
next


# returns an 2-D array where each element is a Rational
def reduced_row_echelon_form(ary)
  lead = 0
  rows = ary.size
  cols = ary[0].size
  rary = convert_to(ary, :to_r)  # use rational arithmetic
  catch :done  do
    rows.times do |r|
      throw :done  if cols <= lead
      i = r
      while rary[i][lead] == 0
        i += 1
        if rows == i
          i = r
          lead += 1
          throw :done  if cols == lead
        end
      end
      # swap rows i and r
      rary[i], rary[r] = rary[r], rary[i]
      # normalize row r
      v = rary[r][lead]
      rary[r].collect! {|x| x / v}
      # reduce other rows
      rows.times do |i|
        next if i == r
        v = rary[i][lead]
        rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]}
      end
      lead += 1
    end
  end
  rary
end

# type should be one of :to_s, :to_i, :to_f, :to_r
def convert_to(ary, type)
  ary.each_with_object([]) do |row, new|
    new << row.collect {|elem| elem.send(type)}
  end
end

class Rational
  alias _to_s to_s
  def to_s
    denominator==1 ? numerator.to_s : _to_s
  end
end

def print_matrix(m)
  max = m[0].collect {-1}
  m.each {|row| row.each_index {|i| max[i] = [max[i], row[i].to_s.length].max}}
  m.each {|row| row.each_index {|i| print "%#{max[i]}s " % row[i]}; puts}
end

mtx = [
  [ 1, 2, -1, -4],
  [ 2, 3, -1,-11],
  [-2, 0, -3, 22]
]
print_matrix reduced_row_echelon_form(mtx)
puts

mtx = [
  [ 1, 2, 3, 7],
  [-4, 7,-2, 7],
  [ 3, 3, 0, 7]
]
reduced = reduced_row_echelon_form(mtx)
print_matrix reduced
print_matrix convert_to(reduced, :to_f)


 %file = new fileObject();
 %file.openForRead("File/Path.txt");
 $seventhLine = "";

 while(!%file.isEOF())
 {
 	%line++;

 	if(%line == 7)
 	{
 		$seventhLine = %file.readLine();

 		if($seventhLine $= "")
 		{
 			error("Line 7 of the file is blank!");
 		}
 	}
 }

 %file.close();
 %file.delete();

 if(%line < 7)
 {
 	error("The file does not have seven lines!");
 }


$$ MODE TUSCRIPT
file="lines.txt"
ERROR/STOP OPEN (file,READ,-std-)
line2fetch=7


get_nth_line() {
    local file=$1 n=$2 line
    while ((n-- > 0)); do
        if ! IFS= read -r line; then
            echo "No such line $2 in $file"
            return 1
        fi
    done < "$file"
    echo "$line"
}

get_nth_line filename 7


decl string<> lines
decl file f
f.open "filename.txt"
set lines (f.readlines)
f.close

if (< (size lines) 7)
        out "the file has less than seven lines" endl console
        stop
end if

out "the seventh line in the file is:" endl endl console
out lines<6> endl console


fn main() {
    let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
                                                vec![2.0, 3.0, -1.0, -11.0],
                                                vec![-2.0, 0.0, -3.0, 22.0]];
    let mut r_mat_to_red = &mut matrix_to_reduce;
    let rr_mat_to_red = &mut r_mat_to_red;

    println!("Matrix to reduce:\n{:?}", rr_mat_to_red);
    let reduced_matrix = reduced_row_echelon_form(rr_mat_to_red);
    println!("Reduced matrix:\n{:?}", reduced_matrix);
}

fn reduced_row_echelon_form(matrix: &mut Vec<Vec<f64>>) -> Vec<Vec<f64>> {
    let mut matrix_out: Vec<Vec<f64>> = matrix.to_vec();
    let mut pivot = 0;
    let row_count = matrix_out.len();
    let column_count = matrix_out[0].len();

    'outer: for r in 0..row_count {
        if column_count <= pivot {
            break;
        }
        let mut i = r;
        while matrix_out[i][pivot] == 0.0 {
            i = i+1;
            if i == row_count {
                i = r;
                pivot = pivot + 1;
                if column_count == pivot {
                    pivot = pivot - 1;
                    break 'outer;
                }
            }
        }
        for j in 0..row_count {
            let temp = matrix_out[r][j];
            matrix_out[r][j] = matrix_out[i][j];
            matrix_out[i][j] = temp;
        }
        let divisor = matrix_out[r][pivot];
        if divisor != 0.0 {
            for j in 0..column_count {
                matrix_out[r][j] = matrix_out[r][j] / divisor;
            }
        }
        for j in 0..row_count {
            if j != r {
                let hold = matrix_out[j][pivot];
                for k in 0..column_count {
                    matrix_out[j][k] = matrix_out[j][k] - ( hold * matrix_out[r][k]);
                }
            }
        }
        pivot = pivot + 1;
    }
    matrix_out
}


(define (reduced-row-echelon-form matrix)
  (define (clean-down matrix from-row column)
    (cons (car matrix)
          (if (zero? from-row)
              (map (lambda (row)
                     (map -
                          row
                          (map (lambda (element)
                                 (/ (* element (list-ref row column))
                                    (list-ref (car matrix) column)))
                               (car matrix))))
                   (cdr matrix))
              (clean-down (cdr matrix) (- from-row 1) column))))
  (define (clean-up matrix until-row column)
    (if (zero? until-row)
        matrix
        (cons (map -
                   (car matrix)
                   (map (lambda (element)
                          (/ (* element (list-ref (car matrix) column))
                             (list-ref (list-ref matrix until-row) column)))
                        (list-ref matrix until-row)))
              (clean-up (cdr matrix) (- until-row 1) column))))
  (define (normalise matrix row with-column)
    (if (zero? row)
        (cons (map (lambda (element)
                     (/ element (list-ref (car matrix) with-column)))
                   (car matrix))
              (cdr matrix))
        (cons (car matrix) (normalise (cdr matrix) (- row 1) with-column))))
  (define (repeat procedure matrix indices)
    (if (null? indices)
        matrix
        (repeat procedure
                (procedure matrix (car indices) (car indices))
                (cdr indices))))
  (define (iota start stop)
    (if (> start stop)
        (list)
        (cons start (iota (+ start 1) stop))))
  (let ((indices (iota 0 (- (length matrix) 1))))
    (repeat normalise
            (repeat clean-up
                    (repeat clean-down
                            matrix
                            indices)
                    indices)
            indices)))


Function read_line(filepath,n)
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objFile = objFSO.OpenTextFile(filepath,1)
	arrLines = Split(objFile.ReadAll,vbCrLf)
	If UBound(arrLines) >= n-1 Then
		If arrLines(n-1) <> "" Then
			read_line = arrLines(n-1)
		Else
			read_line = "Line " & n & " is null."
		End If
	Else
		read_line = "Line " & n & " does not exist."
	End If
	objFile.Close
	Set objFSO = Nothing
End Function

WScript.Echo read_line("c:\temp\input.txt",7)


File_Open("example.txt", BROWSE)
Goto_Line(7)
if (Cur_Line < 7) {
    Statline_Message("File contains too few lines")
} else {
    if (At_EOL) {
        Statline_Message("Empty line")
    }
    Reg_Copy(10, 1)
}
Buf_Close(NOMSG)


import "io" for File

var lines = File.read("input.txt").replace("\r", "").split("\n")
if (lines.count < 7) {
    System.print("There are only %(lines.count) lines in the file")
} else {
    var line7 = lines[6].trim()
    if (line7 == "") {
        System.print("The seventh line is empty")
    } else {
        System.print("The seventh line is : %(line7)")
    }
}

/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/


const type: matrix is array array float;

const proc: toReducedRowEchelonForm (inout matrix: mat) is func
  local
    var integer: numRows is 0;
    var integer: numColumns is 0;
    var integer: row is 0;
    var integer: column is 0;
    var integer: pivot is 0;
    var float: factor is 0.0;
  begin
    numRows := length(mat);
    numColumns := length(mat[1]);
    for row range numRows downto 1 do
      column := 1;
      while column <= numColumns and mat[row][column] = 0.0 do
        incr(column);
      end while;
      if column > numColumns then
        # Empty rows are moved to the bottom
        mat := mat[.. pred(row)] & mat[succ(row) ..] & [] (mat[row]);
        decr(numRows);
      end if;
    end for;
    for pivot range 1 to numRows do
      if mat[pivot][pivot] = 0.0 then
        # Find a row were the pivot column is not zero
        row := 1;
        while row <= numRows and mat[row][pivot] = 0.0 do
          incr(row);
        end while;
        # Add row were the pivot column is not zero
        for column range 1 to numColumns do
          mat[pivot][column] +:= mat[row][column];
        end for;
      end if;
      if mat[pivot][pivot] <> 1.0 then
        # Make sure that the pivot element is 1.0
        factor := 1.0 / mat[pivot][pivot];
        for column range pivot to numColumns do
          mat[pivot][column] := mat[pivot][column] * factor;
        end for;
      end if;
      for row range 1 to numRows do
        if row <> pivot and mat[row][pivot] <> 0.0 then
          # Make sure that in all other rows the pivot column contains zero
          factor := -mat[row][pivot];
          for column range pivot to numColumns do
            mat[row][column] +:= mat[pivot][column] * factor;
          end for;
        end if;
      end for;
    end for;
  end func;


func rref (M) {
    var (j, rows, cols) = (0, M.len, M[0].len)

    for r in (^rows) {
        j < cols || return M

        var i = r
        while (!M[i][j]) {
            ++i == rows || next
            i = r
            ++j == cols && return M
        }

        M[i, r] = M[r, i] if (r != i)
        M[r] = (M[r] »/» M[r][j])

        for n in (^rows) {
            next if (n == r)
            M[n] = (M[n] »-« (M[r] »*» M[n][j]))
        }
        ++j
    }

    return M
}

func say_it (message, array) {
    say "\n#{message}";
    array.each { |row|
        say row.map { |n| " %5s" % n.as_rat }.join
    }
}

var M = [
    [ # base test case
      [  1,  2,  -1,  -4 ],
      [  2,  3,  -1, -11 ],
      [ -2,  0,  -3,  22 ],
    ],
    [ # mix of number styles
      [  3,   0,  -3,    1 ],
      [ .5, 3/2,  -3,   -2 ],
      [ .2, 4/5,  -1.6, .3 ],
    ],
    [ # degenerate case
      [ 1,  2,  3,  4,  3,  1],
      [ 2,  4,  6,  2,  6,  2],
      [ 3,  6, 18,  9,  9, -6],
      [ 4,  8, 12, 10, 12,  4],
      [ 5, 10, 24, 11, 15, -4],
    ],
];

M.each { |matrix|
    say_it('Original Matrix', matrix);
    say_it('Reduced Row Echelon Form Matrix', rref(matrix));
    say '';
}


include c:\cxpl\codes;  \intrinsic 'code' declarations
def MaxLen = 82;        \maximum length of line that can be stored (incl CR+LF)

func ReadLine(N, L);    \Read line N from input file and return it in string L
int  N;  char L;
int  I, C;
[for I:= 1 to N-1 do    \skip to start of specified line
        repeat  C:= ChIn(1);
                if C = $1A\EOF\ then
                        [Text(0, "File only has ");  IntOut(0, I);
                        Text(0, " lines^M^J");  return false];
        until   C = $0A\LF\;
I:= 0;
repeat  C:= ChIn(1);
        if C = $1A\EOF\ then
                [Text(0, "Line is empty (EOF)^M^L");  return false];
        L(I):= C;  I:= I+1;
until   C=$0A\LF\ or I>=MaxLen;
if I >= MaxLen then Text(0, "Line might be truncated^M^J");
if I = 2 then Text(0, "Line is empty^M^J");
L(I-1):= L(I-1) ! $80;          \terminate string
return true;
];

char LineN(MaxLen);
if ReadLine(7, LineN) then Text(0, LineN)


reg line; do(7){line=File.stdin.readln()} println(">>>",line);


        var lead = 0
        for r in 0..<rows {
            if (cols <= lead) { break }
            var i = r
            while (m[i][lead] == 0) {
                i += 1
                if (i == rows) {
                    i = r
                    lead += 1
                    if (cols == lead) {
                        lead -= 1
                        break
                    }
                }
            }
            for j in 0..<cols {
                let temp = m[r][j]
                m[r][j] = m[i][j]
                m[i][j] = temp
            }
            let div = m[r][lead]
            if (div != 0) {
                for j in 0..<cols {
                    m[r][j] /= div
                }
            }
            for j in 0..<rows {
                if (j != r) {
                    let sub = m[j][lead]
                    for k in 0..<cols {
                        m[j][k] -= (sub * m[r][k])
                    }
                }
            }
            lead += 1
        }


package require Tcl 8.5
namespace path {::tcl::mathop ::tcl::mathfunc}

proc toRREF {m} {
    set lead 0
    lassign [size $m] rows cols
    for {set r 0} {$r < $rows} {incr r} {
        if {$cols <= $lead} {
            break
        }
        set i $r
        while {[lindex $m $i $lead] == 0} {
            incr i
            if {$rows == $i} {
                set i $r
                incr lead
                if {$cols == $lead} {
                    # Tcl can't break out of nested loops
                    return $m
                }
            }
        }
        # swap rows i and r
        foreach idx [list $i $r] row [list [lindex $m $r] [lindex $m $i]] {
            lset m $idx $row
        }
        # divide row r by m(r,lead)
        set val [lindex $m $r $lead]
        for {set j 0} {$j < $cols} {incr j} {
            lset m $r $j [/ [double [lindex $m $r $j]] $val]
        }

        for {set i 0} {$i < $rows} {incr i} {
            if {$i != $r} {
                # subtract m(i,lead) multiplied by row r from row i
                set val [lindex $m $i $lead]
                for {set j 0} {$j < $cols} {incr j} {
                    lset m $i $j [- [lindex $m $i $j] [* $val [lindex $m $r $j]]]
                }
            }
        }
        incr lead
    }
    return $m
}

set m {{1 2 -1 -4} {2 3 -1 -11} {-2 0 -3 22}}
print_matrix $m
print_matrix [toRREF $m]


#import std
#import flo

pivot      = -<x fleq+ abs~~bh
descending = ~&a^&+ ^|ahPathS2fattS2RpC/~&
reflect    = ~&lxPrTSx+ *iiD ~&l-~brS+ zipp0
row_reduce = ^C/vid*hhiD *htD minus^*p/~&r times^*D/[email protected] ~&l
rref       = reflect+ (descending row_reduce)+ reflect+ descending row_reduce+ pivot

#show+

test =

printf/*=*'%8.4f' rref <
   <1.,2.,-1.,-4.>,
   <2.,3.,-1.,-11.>,
   <-2.,0.,-3.,22.>>


Private Function ToReducedRowEchelonForm(M As Variant) As Variant
    Dim lead As Integer: lead = 0
    Dim rowCount As Integer: rowCount = UBound(M)
    Dim columnCount As Integer: columnCount = UBound(M(0))
    Dim i As Integer
    For r = 0 To rowCount
        If lead >= columnCount Then
            Exit For
        End If
        i = r
        Do While M(i)(lead) = 0
            i = i + 1
            If i = rowCount Then
                i = r
                lead = lead + 1
                If lead = columnCount Then
                    Exit For
                End If
            End If
        Loop
        Dim tmp As Variant
        tmp = M(r)
        M(r) = M(i)
        M(i) = tmp
        If M(r)(lead) <> 0 Then
            div = M(r)(lead)
            For t = LBound(M(r)) To UBound(M(r))
                M(r)(t) = M(r)(t) / div
            Next t
        End If
        For j = 0 To rowCount
            If j <> r Then
                subt = M(j)(lead)
                For t = LBound(M(j)) To UBound(M(j))
                    M(j)(t) = M(j)(t) - subt * M(r)(t)
                Next t
            End If
        Next j
        lead = lead + 1
    Next r
    ToReducedRowEchelonForm = M
End Function

Public Sub main()
    r = ToReducedRowEchelonForm(Array( _
        Array(1, 2, -1, -4), _
        Array(2, 3, -1, -11), _
        Array(-2, 0, -3, 22)))
    For i = LBound(r) To UBound(r)
        Debug.Print Join(r(i), vbTab)
    Next i
End Sub


CLOSE DATABASES ALL
LOCAL lnRows As Integer, lnCols As Integer, lcSafety As String
LOCAL ARRAY matrix[1]
lcSafety = SET("Safety")
SET SAFETY OFF
CLEAR
CREATE CURSOR results (c1 B(6), c2 B(6), c3 B(6), c4 B(6))
CREATE CURSOR curs1(c1 I, c2 I, c3 I, c4 I)
INSERT INTO curs1 VALUES (1,2,-1,-4)
INSERT INTO curs1 VALUES (2,3,-1,-11)
INSERT INTO curs1 VALUES (-2,0,-3,22)
lnRows = RECCOUNT()	&& 3
lnCols = FCOUNT()	&& 4
SELECT * FROM curs1 INTO ARRAY matrix
IF RREF(@matrix, lnRows, lnCols)
	SELECT results
	APPEND FROM ARRAY matrix
	BROWSE NORMAL IN SCREEN
ENDIF
SET SAFETY &lcSafety

FUNCTION RREF(mat, tnRows As Integer, tnCols As Integer) As Boolean
LOCAL lnPivot As Integer, i As Integer, r As Integer, j As Integer, ;
p As Double. llResult As Boolean, llExit As Boolean
llResult = .T.
llExit = .F.
lnPivot = 1
FOR r = 1 TO tnRows
	IF lnPivot > tnCols
		EXIT
	ENDIF
	i = r
	DO WHILE mat[i,lnPivot] = 0
		i = i + 1
		IF i = tnRows
			i = r
			lnPivot = lnPivot + 1
			IF lnPivot > tnCols
				llExit = .T.
				EXIT
			ENDIF
		ENDIF
	ENDDO
	IF llExit
		EXIT
	ENDIF
	ASwapRows(@mat, i, r)
	p = mat[r,lnPivot]
	IF p # 0
		FOR j = 1 TO tnCols
			mat[r,j] = mat[r,j]/p
		ENDFOR
	ELSE
		? "Divison by zero."
		llResult = .F.
		EXIT
	ENDIF
	FOR i = 1 TO tnRows
		IF i # r
			p = mat[i,lnPivot]
			FOR j = 1 TO tnCols
				mat[i,j] = mat[i,j] - mat[r,j]*p
			ENDFOR
		ENDIF
	ENDFOR
	lnPivot = lnPivot + 1
ENDFOR
RETURN llResult
ENDFUNC

PROCEDURE ASwapRows(arr, tnRow1 As Integer, tnRow2 As Integer)
*!* Interchange rows tnRow1 and tnRow2 of array arr.
LOCAL n As Integer
n = ALEN(arr,2)
LOCAL ARRAY tmp[1,n]
STORE 0 TO tmp
ACPY2(@arr, @tmp, tnRow1, 1)
ACPY2(@arr, @arr, tnRow2, tnRow1)
ACPY2(@tmp, @arr, 1, tnRow2)
ENDPROC

PROCEDURE ACPY2(m1, m2, tnSrcRow As Integer, tnDestRow As Integer)
*!* Copy m1[tnSrcRow,*] to m2[tnDestRow,*]
*!* m1 and m2 must have the same number of columns.
LOCAL n As Integer, e1 As Integer, e2 As Integer
n = ALEN(m1,2)
e1 = AELEMENT(m1,tnSrcRow,1)
e2 = AELEMENT(m2,tnDestRow,1)
ACOPY(m1, m2, e1, n, e2)
ENDPROC


import "/matrix" for Matrix
import "/fmt" for Fmt

var m = Matrix.new([
    [ 1,  2,  -1,  -4],
    [ 2,  3,  -1, -11],
    [-2,  0,  -3,  22]
])

System.print("Original:\n")
Fmt.mprint(m, 3, 0)
System.print("\nRREF:\n")
m.toReducedRowEchelonForm
Fmt.mprint(m, 3, 0)


// Rosetta Code problem: https://rosettacode.org/wiki/Reduced_row_echelon_form
// by Jjuanhdez, 06/2022

dim matrix (3, 4)
matrix(1, 1) =  1 : matrix(1, 2) = 2 : matrix(1, 3) = -1 : matrix(1, 4) = -4
matrix(2, 1) =  2 : matrix(2, 2) = 3 : matrix(2, 3) = -1 : matrix(2, 4) = -11
matrix(3, 1) = -2 : matrix(3, 2) = 0 : matrix(3, 3) = -3 : matrix(3, 4) =  22

RREF (matrix())

for row = 1 to 3
    for col = 1 to 4
        if matrix(row, col) = 0 then
            print "0", chr$(9);
        else
            print matrix(row, col), chr$(9);
        end if
    next
    print
next
end

sub RREF(x())
    local nrows, ncols, lead, r, i, j, n
    nrows = arraysize(matrix(), 1)  //3
    ncols = arraysize(matrix(), 2)  //4
    lead = 1
    for r = 1 to nrows
        if lead >= ncols  break
        i = r
        while matrix(i, lead) = 0
            i = i + 1
            if i = nrows then
                i = r
                lead = lead + 1
                if lead = ncols break 2
            end if
        wend
        for j = 1 to ncols
            temp = matrix(i, j)
            matrix(i, j) = matrix(r, j)
            matrix(r, j) = temp
        next
        n = matrix(r, lead)
        if n <> 0 then
            for j = 1 to ncols
                matrix(r, j) = matrix(r, j) / n
            next
        end if
        for i = 1 to nrows
            if i <> r then
                n = matrix(i, lead)
                for j = 1 to ncols
                    matrix(i, j) = matrix(i, j) - matrix(r, j) * n
                next
            end if
        next
        lead = lead + 1
    next
end sub


*        Read a file line by line  12/06/2016
READFILE CSECT
         SAVE  (14,12)             save registers on entry
         PRINT NOGEN
         BALR  R12,0               establish addressability
         USING *,R12               set base register
         ST    R13,SAVEA+4         link mySA->prevSA
         LA    R11,SAVEA           mySA
         ST    R11,8(R13)          link prevSA->mySA
         LR    R13,R11             set mySA pointer
         OPEN  (INDCB,INPUT)       open the input file
         OPEN  (OUTDCB,OUTPUT)     open the output file
LOOP     GET   INDCB,PG            read record
         CLI   EOFFLAG,C'Y'        eof reached?
         BE    EOF
         PUT   OUTDCB,PG           write record
         B     LOOP
EOF      CLOSE (INDCB)             close input
         CLOSE (OUTDCB)            close output
         L     R13,SAVEA+4         previous save area addrs
         RETURN (14,12),RC=0       return to caller with rc=0
INEOF    CNOP  0,4                 end-of-data routine
         MVI   EOFFLAG,C'Y'        set the end-of-file flag
         BR    R14                 return to caller
SAVEA    DS    18F                 save area for chaining
INDCB    DCB   DSORG=PS,MACRF=PM,DDNAME=INDD,LRECL=80,                 *
               RECFM=FB,EODAD=INEOF
OUTDCB   DCB   DSORG=PS,MACRF=PM,DDNAME=OUTDD,LRECL=80,                *
               RECFM=FB
EOFFLAG  DC    C'N'                end-of-file flag
PG       DS    CL80                buffer
         YREGS
         END   READFILE


var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
fcn toReducedRowEchelonForm(M){  // in place
   lead,rows,columns := 0,M.rows,M.cols;
   foreach r in (rows){
      if (columns<=lead) return(M);
      i:=r;
      while(M[i,lead]==0){  // not a great check to use with real numbers
	 i+=1;
	 if(i==rows){
	    i=r; lead+=1;
	    if(lead==columns) return(M);
	 }
      }
      M.swapRows(i,r);
      if(x:=M[r,lead]) M[r]/=x;
      foreach i in (rows){ if(i!=r) M[i]-=M[r]*M[i,lead] }
      lead+=1;
   }
   M
}


"path/to/file" f:open ( . cr ) f:eachline f:close


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program readfile64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ BUFFERSIZE,          1000
.equ LINESIZE,            100

/*******************************************/
/* Structures                               */
/********************************************/
/* structure read file*/
    .struct  0
readfile_Fd:                           // File descriptor
    .struct  readfile_Fd + 8
readfile_buffer:                       // read buffer
    .struct  readfile_buffer + 8
readfile_buffersize:                   // buffer size
    .struct  readfile_buffersize + 8
readfile_line:                         // line buffer
    .struct  readfile_line + 8
readfile_linesize:                     // line buffer size
    .struct  readfile_linesize + 8
readfile_pointer:
    .struct  readfile_pointer + 8      // read pointer  (init to buffer size + 1)
readfile_end:
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szFileName:              .asciz "fictest.txt"
szCarriageReturn:        .asciz "\n"
/* datas error display */
szMessError:           .asciz "Error detected : @ \n"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sBuffer:             .skip BUFFERSIZE             // buffer result
szLineBuffer:        .skip LINESIZE
.align 4
stReadFile:          .skip readfile_end
sZoneConv:           .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:
    mov x0,AT_FDCWD
    ldr x1,qAdrszFileName              // File name
    mov x2,O_RDWR                      //  flags
    mov x3,0                           // mode
    mov x8,OPEN                        // open file
    svc 0
    cmp x0,0                           // error ?
    ble error
    ldr x21,qAdrstReadFile              // init struture readfile
    str x0,[x21,readfile_Fd]            // save FD in structure
    ldr x0,qAdrsBuffer                 // buffer address
    str x0,[x21,readfile_buffer]
    mov x0,BUFFERSIZE                  // buffer size
    str x0,[x21,readfile_buffersize]
    ldr x0,qAdrszLineBuffer            // line buffer address
    str x0,[x21,readfile_line]
    mov x0,LINESIZE                    // line buffer size
    str x0,[x21,readfile_linesize]
    mov x0,BUFFERSIZE + 1              // init read pointer
    str x0,[x21,readfile_pointer]
1:                                     // begin read loop
    mov x0,x21
    bl readLineFile
    cmp x0,0
    beq end                             // end loop
    blt error

    ldr x0,qAdrszLineBuffer             //  display line
    bl affichageMess
    ldr x0,qAdrszCarriageReturn         // display line return
    bl affichageMess
    b 1b                                // and loop

end:
    ldr x1,qAdrstReadFile
    ldr x0,[x1,readfile_Fd]            // load FD to structure
    mov x8,CLOSE                        // call system close file
    svc 0
    cmp x0,0
    blt error
    mov x0,0                           // return code
    b 100f
error:
    ldr x1,qAdrsZoneConv
    bl conversion10S
    ldr x0,qAdrszMessError             // error message
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc               // insert result at @ character
    bl  affichageMess
    mov x0,1                           // return error code
100:                                    // standard end of the program
    mov x8,EXIT                       // request to exit program
    svc 0                               // perform system call
qAdrsBuffer:               .quad sBuffer
qAdrszFileName:            .quad szFileName
qAdrszMessError:           .quad szMessError
qAdrsZoneConv:             .quad sZoneConv
qAdrszCarriageReturn:      .quad szCarriageReturn
qAdrstReadFile:            .quad stReadFile
qAdrszLineBuffer:          .quad szLineBuffer
/******************************************************************/
/*     sub strings  index start  number of characters             */
/******************************************************************/
/* x0 contains the address of the structure */
/* x0 returns number of characters or -1 if error */
readLineFile:
    stp x1,lr,[sp,-16]!                        // save  registers
    mov x14,x0                                 // save structure
    ldr x11,[x14,#readfile_buffer]
    ldr x12,[x14,#readfile_buffersize]
    ldr x15,[x14,#readfile_pointer]
    ldr x16,[x14,#readfile_linesize]
    ldr x18,[x14,#readfile_buffersize]
    ldr x10,[x14,#readfile_line]
    mov x13,0
    strb wzr,[x10,x13]                          // store zéro in line buffer
    cmp x15,x12                                 // pointer buffer < buffer size ?
    ble 2f                                      // no file read
1:                                              // loop read file
    ldr x0,[x14,#readfile_Fd]
    mov x1,x11                                  // buffer address
    mov x2,x12                                  // buffer size
    mov x8,READ                                 // call system read file
    svc 0
    cmp x0,#0                                   // error read or end ?
    ble 100f
    mov x18,x0                                  // number of read characters
    mov x15,#0                                  // init buffer pointer

2:                                              // begin loop copy characters
    ldrb w0,[x11,x15]                           // load 1 character read buffer
    cmp x0,0x0A                                 // end line ?
    beq 4f
    strb w0,[x10,x13]                           // store character in line buffer
    add x13,x13,1                               // increment pointer line
    cmp x13,x16
    bgt 99f                                      // error
    add x15,x15,1                                // increment buffer pointer
    cmp x15,x12                                  // end buffer ?
    bge 1b                                       // yes new read
    cmp x15,x18                                  // read characters ?
    blt 2b                                       // no loop
                                                 // final
    cmp x13,0                                    // no characters in line buffer ?
    beq 100f
4:
    strb wzr,[x10,x13]                           // store zéro final
    add x15,x15,#1
    str x15,[x14,#readfile_pointer]              // store pointer in structure
    str x18,[x14,#readfile_buffersize]           // store number of last characters
    mov x0,x13                                   // return length of line
    b 100f
99:
    mov x0,#-2                                   // line buffer too small -> error
100:

    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


char array TXT

Proc Main()

 Open (1,"D:FILENAME.TXT",4,0)
 Do
  InputSD(1,TXT)
  PrintE(TXT)
  Until EOF(1)
 Od
 Close(1)

Return


with Ada.Text_IO;  use Ada.Text_IO;

procedure Line_By_Line is
   File : File_Type;
begin
   Open (File => File,
         Mode => In_File,
         Name => "line_by_line.adb");
   While not  End_Of_File (File) Loop
      Put_Line (Get_Line (File));
   end loop;

   Close (File);
end Line_By_Line;


file f;
text s;

f.affix("src/aime.c");

while (f.line(s) != -1) {
    o_text(s);
    o_byte('\n');
}


#!/usr/local/bin/a68g --script #

FILE foobar;
INT errno = open(foobar, "Read_a_file_line_by_line.a68", stand in channel);

STRING line;
FORMAT line fmt = $gl$;

PROC mount next tape = (REF FILE file)BOOL: (
  print("Please mount next tape or q to quit");
  IF read char = "q" THEN done ELSE TRUE FI
);

on physical file end(foobar, mount next tape);
on logical file end(foobar, (REF FILE skip)BOOL: done);

FOR count DO
  getf(foobar, (line fmt, line));
  printf(($g(0)": "$, count, line fmt, line))
OD;
done: SKIP


⍝⍝ GNU APL Version
∇listFile fname ;fileHandle;maxLineLen;line
  maxLineLen ← 128
  fileHandle ← ⎕FIO['fopen'] fname
readLoop:
  →(0=⍴(line ← maxLineLen ⎕FIO['fgets'] fileHandle))/eof
  ⍞ ← ⎕AV[1+line]  ⍝⍝ bytes to ASCII
  → readLoop
eof:
  ⊣⎕FIO['fclose'] fileHandle
  ⊣⎕FIO['errno'] fileHandle
∇

      listFile 'corpus/sample1.txt'
This is some sample text.
The text itself has multiple lines, and
the text has some words that occur multiple times
in the text.

This is the end of the text.


#include <hopper.h>

main:
   .ctrlc
   fd=0
   fopen(OPEN_READ,"archivo.txt")(fd)
   if file error?
      {"Error open file: "},file error
   else
      line read=0
      while( not(feof(fd)))
         fread line(1000)(fd), ++line read
         println
      wend
      {"Total read lines : ",line read}
      fclose(fd)
   endif
   println
exit(0)


/* ARM assembly Raspberry PI  */
/*  program readfile.s   */

/* Constantes    */
.equ STDOUT, 1                           @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ READ,   3
.equ WRITE,  4
.equ OPEN,   5
.equ CLOSE,  6

.equ O_RDWR,  0x0002                    @ open for reading and writing

.equ BUFFERSIZE,          100
.equ LINESIZE,            100

/*******************************************/
/* Structures                               */
/********************************************/
/* structure read file*/
    .struct  0
readfile_Fd:                           @ File descriptor
    .struct  readfile_Fd + 4
readfile_buffer:                       @ read buffer
    .struct  readfile_buffer + 4
readfile_buffersize:                   @ buffer size
    .struct  readfile_buffersize + 4
readfile_line:                         @ line buffer
    .struct  readfile_line + 4
readfile_linesize:                     @ line buffer size
    .struct  readfile_linesize + 4
readfile_pointer:
    .struct  readfile_pointer + 4      @ read pointer  (init to buffer size + 1)
readfile_end:
/* Initialized data */
.data
szFileName:              .asciz "fictest.txt"
szCarriageReturn:        .asciz "\n"
/* datas error display */
szMessErreur:        .asciz "Error detected.\n"
szMessErr:           .ascii "Error code hexa : "
sHexa:               .space 9,' '
                     .ascii "  decimal :  "
sDeci:               .space 15,' '
                     .asciz "\n"

/* UnInitialized data */
.bss
sBuffer:             .skip BUFFERSIZE             @ buffer result
szLineBuffer:        .skip LINESIZE
.align 4
stReadFile:          .skip readfile_end

/*  code section */
.text
.global main
main:
    ldr r0,iAdrszFileName               @ File name
    mov r1,#O_RDWR                      @  flags
    mov r2,#0                           @ mode
    mov r7,#OPEN                        @ open file
    svc #0
    cmp r0,#0                           @ error ?
    ble error
    ldr r1,iAdrstReadFile               @ init struture readfile
    str r0,[r1,#readfile_Fd]            @ save FD in structure
    ldr r0,iAdrsBuffer                  @ buffer address
    str r0,[r1,#readfile_buffer]
    mov r0,#BUFFERSIZE                  @ buffer size
    str r0,[r1,#readfile_buffersize]
    ldr r0,iAdrszLineBuffer             @ line buffer address
    str r0,[r1,#readfile_line]
    mov r0,#LINESIZE                    @ line buffer size
    str r0,[r1,#readfile_linesize]
    mov r0,#BUFFERSIZE + 1              @ init read pointer
    str r0,[r1,#readfile_pointer]
1:                                      @ begin read loop
    mov r0,r1
    bl readLineFile
    cmp r0,#0
    beq end                             @ end loop
    blt error

    ldr r0,iAdrszLineBuffer             @  display line
    bl affichageMess
    ldr r0,iAdrszCarriageReturn         @ display line return
    bl affichageMess
    b 1b                                @ and loop

end:
    ldr r1,iAdrstReadFile
    ldr r0,[r1,#readfile_Fd]            @ load FD to structure
    mov r7, #CLOSE                      @ call system close file
    svc #0
    cmp r0,#0
    blt error
    mov r0,#0                           @ return code
    b 100f
error:
    ldr r1,iAdrszMessErreur             @ error message
    bl   displayError
    mov r0,#1                           @ return error code
100:                                    @ standard end of the program
    mov r7, #EXIT                       @ request to exit program
    svc 0                               @ perform system call
iAdrsBuffer:               .int sBuffer
iAdrszFileName:            .int szFileName
iAdrszMessErreur:          .int szMessErreur
iAdrszCarriageReturn:      .int szCarriageReturn
iAdrstReadFile:            .int stReadFile
iAdrszLineBuffer:          .int szLineBuffer
/******************************************************************/
/*     sub strings  index start  number of characters             */
/******************************************************************/
/* r0 contains the address of the structure */
/* r0 returns number of characters or -1 if error */
readLineFile:
    push {r1-r8,lr}                             @ save  registers
    mov r4,r0                                   @ save structure
    ldr r1,[r4,#readfile_buffer]
    ldr r2,[r4,#readfile_buffersize]
    ldr r5,[r4,#readfile_pointer]
    ldr r6,[r4,#readfile_linesize]
    ldr r7,[r4,#readfile_buffersize]
    ldr r8,[r4,#readfile_line]
    mov r3,#0                                   @ line pointer
    strb r3,[r8,r3]                             @ store zéro in line buffer
    cmp r5,r2                                   @ pointer buffer < buffer size ?
    ble 2f                                      @ no file read
1:                                              @ loop read file
    ldr r0,[r4,#readfile_Fd]
    mov r7,#READ                                @ call system read file
    svc 0
    cmp r0,#0                                   @ error read or end ?
    ble 100f
    mov r7,r0                                   @ number of read characters
    mov r5,#0                                   @ init buffer pointer

2:                                              @ begin loop copy characters
    ldrb r0,[r1,r5]                             @ load 1 character read buffer
    cmp r0,#0x0A                                @ end line ?
    beq 4f
    strb r0,[r8,r3]                             @ store character in line buffer
    add r3,#1                                   @ increment pointer line
    cmp r3,r6
    movgt r0,#-2                                @ line buffer too small -> error
    bgt 100f
    add r5,#1                                   @ increment buffer pointer
    cmp r5,r2                                   @ end buffer ?
    bge 1b                                      @ yes new read
    cmp r5,r7                                   @ read characters ?
    blt 2b                                      @ no loop
                                                @ final
    cmp r3,#0                                   @ no characters in line buffer ?
    beq 100f
4:
    mov r0,#0
    strb r0,[r8,r3]                             @ store zéro final
    add r5,#1
    str r5,[r4,#readfile_pointer]               @ store pointer in structure
    str r7,[r4,#readfile_buffersize]            @ store number of last characters
    mov r0,r3                                   @ return length of line
100:
    pop {r1-r8,lr}                              @ restaur registers
    bx lr                                       @ return

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call system
    pop {r0,r1,r2,r7,lr}                        @ restaur registers
    bx lr                                       @ return
/***************************************************/
/*   display error message                        */
/***************************************************/
/* r0 contains error code  r1 : message address */
displayError:
    push {r0-r2,lr}                         @ save registers
    mov r2,r0                               @ save error code
    mov r0,r1
    bl affichageMess
    mov r0,r2                               @ error code
    ldr r1,iAdrsHexa
    bl conversion16                         @ conversion hexa
    mov r0,r2                               @ error code
    ldr r1,iAdrsDeci                        @ result address
    bl conversion10S                        @ conversion decimale
    ldr r0,iAdrszMessErr                    @ display error message
    bl affichageMess
100:
    pop {r0-r2,lr}                          @ restaur registers
    bx lr                                   @ return
iAdrszMessErr:                 .int szMessErr
iAdrsHexa:                     .int sHexa
iAdrsDeci:                     .int sDeci
/******************************************************************/
/*     Converting a register to hexadecimal                      */
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion16:
    push {r1-r4,lr}                          @ save registers
    mov r2,#28                               @ start bit position
    mov r4,#0xF0000000                       @ mask
    mov r3,r0                                @ save entry value
1:                                           @ start loop
    and r0,r3,r4                             @ value register and mask
    lsr r0,r2                                @ move right
    cmp r0,#10                               @ compare value
    addlt r0,#48                             @ <10  ->digit
    addge r0,#55                             @ >10  ->letter A-F
    strb r0,[r1],#1                          @ store digit on area and + 1 in area address
    lsr r4,#4                                @ shift mask 4 positions
    subs r2,#4                               @ counter bits - 4 <= zero  ?
    bge 1b                                   @ no -> loop

100:
    pop {r1-r4,lr}                                     @ restaur registers
    bx lr
/***************************************************/
/*  Converting a register to a signed decimal      */
/***************************************************/
/* r0 contains value and r1 area address    */
conversion10S:
    push {r0-r4,lr}       @ save registers
    mov r2,r1             @ debut zone stockage
    mov r3,#'+'           @ par defaut le signe est +
    cmp r0,#0             @ negative number ?
    movlt r3,#'-'         @ yes
    mvnlt r0,r0           @ number inversion
    addlt r0,#1
    mov r4,#10            @ length area
1:                        @ start loop
    bl divisionpar10U
    add r1,#48            @ digit
    strb r1,[r2,r4]       @ store digit on area
    sub r4,r4,#1          @ previous position
    cmp r0,#0             @ stop if quotient = 0
    bne 1b

    strb r3,[r2,r4]       @ store signe
    subs r4,r4,#1         @ previous position
    blt  100f             @ if r4 < 0 -> end

    mov r1,#' '           @ space
2:
    strb r1,[r2,r4]       @store byte space
    subs r4,r4,#1         @ previous position
    bge 2b                @ loop if r4 > 0
100:
    pop {r0-r4,lr}        @ restaur registers
    bx lr
/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient    */
/* r1 remainder   */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function
iMagicNumber:  	.int 0xCCCCCCCD


for line in lines open('input.txt'):
    print line


; --> Prompt the user to select the file being read

FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes
If Errorlevel ; If no file selected
	ExitApp

; --> Main loop: Input (File), Output (Text)

Loop
{
FileReadLine, Line, %File%, %A_Index% ; Reads line N (where N is loop iteration)
if Errorlevel ; If line does not exist, break loop
	break
Text .= A_Index ". " Line . "`n" ; Appends the line to the variable "Text", adding line number before & new line after
}

; --> Delivers the output as a text file

FileDelete, Output.txt ; Makes sure output is clear before writing
FileAppend, %Text%, Output.txt ; Writes the result to Output.txt
Run Output.txt ; Shows the created file


' Read a file line by line
filename$ = "readlines.bac"
OPEN filename$ FOR READING AS fh
READLN fl$ FROM fh
WHILE ISFALSE(ENDFILE(fh))
    INCR lines
    READLN fl$ FROM fh
WEND
PRINT lines, " lines in ", filename$
CLOSE FILE fh


f = freefile
filename$ = "file.txt"

open f, filename$

while not eof(f)
    print readline(f)
end while
close f
end


@echo off
rem delayed expansion must be disabled before the FOR command.
setlocal disabledelayedexpansion
for /f "tokens=1* delims=]" %%A in ('type "File.txt"^|find /v /n ""') do (
	set var=%%B
	setlocal enabledelayedexpansion
		echo(!var!
	endlocal
)


      file% = OPENIN("*.txt")
      IF file%=0 ERROR 100, "File could not be opened"
      WHILE NOT EOF#file%
        a$ = GET$#file%
      ENDWHILE
      CLOSE #file%


  fil$("test.txt",r)    { r opens a text file, rb opens a binary file for reading }
& fil$(,STR,\n)         { first argument empty: same as before (i.e. "test.txt") }
                        { if \n were replaced by e.g. "\n\t " we would read word-wise instead }
& 0:?lineno
&   whl
  ' ( fil$:(?line.?sep) { "sep" contains found stop character, i.e. \n }
    & put$(line (1+!lineno:?lineno) ":" !line \n)
    )
& (fil$(,SET,-1)|);     { Setting file position before start closes file, and fails.
                          Therefore the | }


include :file

file.each_line "foobar.txt" { line |
  p line
}


/* Programa: Número mayor de tres números introducidos (Solución 1) */

#include <conio.h>
#include <stdio.h>

int main()
{
    int n1, n2, n3;

    printf( "\n   Introduzca el primer n%cmero (entero): ", 163 );
    scanf( "%d", &n1 );
    printf( "\n   Introduzca el segundo n%cmero (entero): ", 163 );
    scanf( "%d", &n2 );
    printf( "\n   Introduzca el tercer n%cmero (entero): ", 163 );
    scanf( "%d", &n3 );

    if ( n1 >= n2 && n1 >= n3 )
        printf( "\n   %d es el mayor.", n1 );
    else

        if ( n2 > n3 )
            printf( "\n   %d es el mayor.", n2 );
        else
            printf( "\n   %d es el mayor.", n3 );

    getch(); /* Pausa */

    return 0;
}


foreach (string readLine in File.ReadLines("FileName"))
  DoSomething(readLine);


#include <fstream>
#include <string>
#include <iostream>

int main( int argc , char** argv ) {
   int linecount = 0 ;
   std::string line  ;
   std::ifstream infile( argv[ 1 ] ) ; // input file stream
   if ( infile ) {
      while ( getline( infile , line ) ) {
	 std::cout << linecount << ": "
                   << line      << '\n' ;  //supposing '\n' to be line end
	 linecount++ ;
      }
   }
   infile.close( ) ;
   return 0 ;
}


(with-open [r (clojure.java.io/reader "some-file.txt")]
   (doseq [l (line-seq r)]
     (println l)))


start_up = proc ()
    po: stream := stream$primary_output()

    % There is a special type for file names. This ensures that
    % the path is valid; if not, file_name$parse would throw an
    % exception (which we are just ignoring here).
    fname: file_name := file_name$parse("input.txt")

    % File I/O is then done through a stream just like any I/O.
    % If the file were not accessible, stream$open would throw an
    % exception.
    fstream: stream := stream$open(fname, "read")

    count: int := 0  % count the lines
    while true do
        % Read a line. This will end the loop once the end is reached,
        % as the exception handler is outside the loop.
        line: string := stream$getl(fstream)

        % Show the line
        count := count + 1
        stream$putl(po, int$unparse(count) || ": " || line)
    end except when end_of_file:
        % Close the file once we're done
        stream$close(fstream)
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. read-file-line-by-line.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT input-file ASSIGN TO "input.txt"
               ORGANIZATION LINE SEQUENTIAL
               FILE STATUS input-file-status.

       DATA DIVISION.
       FILE SECTION.
       FD  input-file.
       01  input-record PIC X(256).

       WORKING-STORAGE SECTION.
       01  input-file-status PIC 99.
           88  file-is-ok    VALUE 0.
           88  end-of-file   VALUE 10.

       01  line-count        PIC 9(6).

       PROCEDURE DIVISION.
           OPEN INPUT input-file
           IF NOT file-is-ok
               DISPLAY "The file could not be opened."
               GOBACK
           END-IF

           PERFORM VARYING line-count FROM 1 BY 1 UNTIL end-of-file
               READ input-file
               DISPLAY line-count ": " FUNCTION TRIM(input-record)
           END-PERFORM

           CLOSE input-file

           GOBACK
           .


# This module shows two ways to read a file line-by-line in node.js.
fs = require 'fs'

# First, let's keep things simple, and do things synchronously.  This
# approach is well-suited for simple scripts.
do ->
  fn = "read_file.coffee"
  for line in fs.readFileSync(fn).toString().split '\n'
    console.log line
  console.log "DONE SYNC!"

# Now let's complicate things.
#
# Use the following code when files are large, and memory is
# constrained and/or where you want a large amount of concurrency.
#
# Protocol:
#   Call LineByLineReader, which calls back to you with a reader.
#   The reader has two methods.
#      next_line: call to this when you want a new line
#      close: call this when you are done using the file before
#         it has been read completely
#
#   When you call next_line, you must supply two callbacks:
#     line_cb: called back when there is a line of text
#     done_cb: called back when there is no more text in the file
LineByLineReader = (fn, cb) ->
  fs.open fn, 'r', (err, fd) ->
    bufsize = 256
    pos = 0
    text = ''
    eof = false
    closed = false
    reader =
      next_line: (line_cb, done_cb) ->
        if eof
          if text
            last_line = text
            text = ''
            line_cb last_line
          else
            done_cb()
          return

        new_line_index = text.indexOf '\n'
        if new_line_index >= 0
          line = text.substr 0, new_line_index
          text = text.substr new_line_index + 1, text.length - new_line_index - 1
          line_cb line
        else
          frag = new Buffer(bufsize)
          fs.read fd, frag, 0, bufsize, pos, (err, bytesRead) ->
            s = frag.toString('utf8', 0, bytesRead)
            text += s
            pos += bytesRead
            if (bytesRead)
              reader.next_line line_cb, done_cb
            else
              eof = true
              fs.closeSync(fd)
              closed = true
              reader.next_line line_cb, done_cb
        close: ->
          # The reader should call this if they abandon mid-file.
          fs.closeSync(fd) unless closed

    cb reader

# Test our interface here.
do ->
  console.log '---'
  fn = 'read_file.coffee'
  LineByLineReader fn, (reader) ->
    callbacks =
      process_line: (line) ->
         console.log line
         reader.next_line callbacks.process_line, callbacks.all_done
      all_done: ->
        console.log "DONE ASYNC!"
    reader.next_line callbacks.process_line, callbacks.all_done


(with-open-file (input "file.txt")
   (loop for line = (read-line input nil)
      while line do (format t "~a~%" line)))


void main() {
    import std.stdio;

    foreach (line; "read_a_file_line_by_line.d".File.byLine)
        line.writeln;
}