Last active
February 27, 2018 13:48
-
-
Save c-yan/9d4d40b44b58c7601763b173e7369cc1 to your computer and use it in GitHub Desktop.
15. 末尾のN行を出力 自然数Nをコマンドライン引数などの手段で受け取り,入力のうち末尾のN行だけを表示せよ.確認にはtailコマンドを用いよ.
This file contains hidden or 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" | |
| "io" | |
| "os" | |
| "strconv" | |
| ) | |
| func main() { | |
| resultLen, err := strconv.Atoi(os.Args[1]) | |
| if err != nil { | |
| panic(err) | |
| } | |
| file, err := os.Open(os.Args[2]) | |
| if err != nil { | |
| panic(err) | |
| } | |
| defer file.Close() | |
| reader := bufio.NewReader(file) | |
| buffer := make([]string, resultLen) | |
| nextIndex := 0 | |
| for { | |
| line, err := reader.ReadString('\n') | |
| if (err != nil) && (err != io.EOF) { | |
| panic(err) | |
| } | |
| buffer[nextIndex] = line | |
| nextIndex = (nextIndex + 1) % resultLen | |
| if err == io.EOF { | |
| break | |
| } | |
| } | |
| for _, line := range buffer[nextIndex:] { | |
| fmt.Print(line) | |
| } | |
| for _, line := range buffer[:nextIndex] { | |
| fmt.Print(line) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment