Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active April 9, 2018 13:02
Show Gist options
  • Save hyuki/867dc3215958c697bebb934233f92472 to your computer and use it in GitHub Desktop.
Save hyuki/867dc3215958c697bebb934233f92472 to your computer and use it in GitHub Desktop.
行番号付きでファイルを表示
package main
import (
"bufio"
"fmt"
"os"
"log"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s input-filename.txt\n", os.Args[0])
os.Exit(1)
}
file, err := os.Open(os.Args[1])
check(err)
linenumber := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Printf("%d: %s\n", linenumber, scanner.Text())
linenumber++
}
check(scanner.Err())
check(file.Close())
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
@hyuki
Copy link
Author

hyuki commented Apr 9, 2018

$ go build a.go
$ ./a
Usage: ./a input-filename.txt
$ ./a sample.txt
0: Lorem ipsum dolor sit amet, consectetur adipiscing elit,
1: sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
2: Ut enim ad minim veniam,
3: quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
4: Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
5: Excepteur sint occaecat cupidatat non proident,
6: sunt in culpa qui officia deserunt mollit anim id est laborum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment