Created
February 19, 2018 19:19
-
-
Save Samir55/8f5b4142b60feba3f6c925ba2b225d86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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