Skip to content

Instantly share code, notes, and snippets.

@Samir55
Created February 19, 2018 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Samir55/8f5b4142b60feba3f6c925ba2b225d86 to your computer and use it in GitHub Desktop.
Save Samir55/8f5b4142b60feba3f6c925ba2b225d86 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func reverseLine (line string) string {
words := strings.Fields(line)
for i, j := 0, len(words) -1; i < j; i, j = i+1, j-1 {
words[i], words[j] = words[j], words[i]
}
return strings.Join(words, " ")
}
func reverseFile (filePath string) int {
var numLines int = 0
file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
defer file.Close() // Wait till all functions in this scope finish
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
numLines += 1
fmt.Println(reverseLine(line)) // Print the reversed line
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return numLines
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter the file name with the extension")
linePath, _ := reader.ReadString('\n')
linePath = strings.Replace(linePath, "\n", "", -1) // convert CRLF to LF
var numLines = reverseFile(linePath)
fmt.Println("The number of lines is ", numLines)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment