Golang, Print (Write) the Lines back from a file

(Last Updated On: December 2, 2016)

I was refreshing basic Linux commands and found tac was one of the commands rarely used, also found interesting in writing a Go program to Write the lines back from the file. I had thought of writing this program using file pointers or file seek methods and started searching for the packages like io,bufio and finally found ioutil example, enhanced further the same program with adding a for loop.

 package main  
 import (  
      "fmt"  
      "io/ioutil"  
      "log"  
      "strings"  
 )  
 func main() {  
      content, err := ioutil.ReadFile("employee.txt")  
      if err == nil {  
           lines := strings.Split(string(content), "\n")  
           for i := 1; i <= len(lines); i++ {  
                fmt.Println(lines[len(lines)-i])  
           }  
      } else {  
           log.Fatal(err)  
      }  
 }  

Output :



C:\Users\karthik\git\github\Go\src\3weeks-Go>cat employee.txt
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Sanjay  Sysadmin   Technology  $7,000
400  Nisha   Manager    Marketing   $9,500
500  Randy   DBA        Technology  $6,000

C:\Users\karthik\git\github\Go\src\3weeks-Go>go run reverse-test.go
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000