本文整理汇总了Golang中bufio.Scanner.Scan方法的典型用法代码示例。如果您正苦于以下问题:Golang Scanner.Scan方法的具体用法?Golang Scanner.Scan怎么用?Golang Scanner.Scan使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bufio.Scanner
的用法示例。
在下文中一共展示了Scanner.Scan方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: PushFile
func PushFile(host string, port int, fname string) {
var scanner *bufio.Scanner
if len(fname) == 0 {
scanner = bufio.NewScanner(os.Stdin)
} else {
file, err := os.Open(fname)
defer file.Close()
if err != nil {
fmt.Fprintln(os.Stderr, "ERROR", err)
return
}
scanner = bufio.NewScanner(file)
}
addr := fmt.Sprintf("%s:%d", host, port)
conn, err := net.Dial("tcp", addr)
if err != nil {
fmt.Fprintln(os.Stderr, "ERROR:", err)
return
}
for scanner.Scan() {
fmt.Fprintln(conn, scanner.Text())
}
}
示例2: main
func main() {
flag.Parse()
flags := flag.Args()
var text string
var scanner *bufio.Scanner
var err error
if len(flags) > 0 {
file, err := os.Open(flags[0])
if err != nil {
log.Fatal(err)
}
scanner = bufio.NewScanner(file)
} else {
scanner = bufio.NewScanner(os.Stdin)
}
for scanner.Scan() {
text += scanner.Text()
}
err = scanner.Err()
if err != nil {
log.Fatal(err)
}
fmt.Println(text)
}
示例3: main
func main() {
var ifile *bufio.Scanner
if len(os.Args) == 2 {
ifile = rx.MkScanner("-")
} else if len(os.Args) == 3 {
ifile = rx.MkScanner(os.Args[2])
} else {
log.Fatal("usage: rxq \"rexpr\" [file]")
}
spec := os.Args[1]
fmt.Printf("regexp: %s\n", spec)
dfa, err := rx.Compile(spec)
if err != nil {
log.Fatal(err)
}
// load and process candidate strings
for i := 0; ifile.Scan(); i++ {
s := ifile.Text()
if dfa.Accepts(s) != nil {
fmt.Println("accept:", s)
} else {
fmt.Println("REJECT:", s)
}
}
rx.CkErr(ifile.Err())
}
示例4: readFrontMatter
func readFrontMatter(s *bufio.Scanner) map[string]string {
m := make(map[string]string)
infm := false
for s.Scan() {
l := strings.Trim(s.Text(), " ")
if l == "/*---" || l == "---*/" { // The front matter is delimited by 3 dashes and in a block comment
if infm {
// This signals the end of the front matter
return m
} else {
// This is the start of the front matter
infm = true
}
} else if infm {
sections := strings.SplitN(l, ":", 2)
if len(sections) != 2 {
// Invalid front matter line
return nil
}
m[sections[0]] = strings.Trim(sections[1], " ")
} else if l != "" {
// No front matter, quit
return nil
}
}
if err := s.Err(); err != nil {
// The scanner stopped because of an error
return nil
}
return nil
}
示例5: mustAddExtra
func mustAddExtra(prefix string, scanner *bufio.Scanner, ci *crash.Info, die func()) {
scanner.Scan()
if !strings.HasPrefix(scanner.Text(), prefix) {
die()
}
ci.Extra = append(ci.Extra, scanner.Text())
}
示例6: readBoard
func readBoard(scanner *bufio.Scanner) (out board) {
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ",")
out = append(out, parts)
}
return out
}
示例7: orderedRemoval
func orderedRemoval(scanner *bufio.Scanner) {
var entries Entries
rows := 0
count := 0
for scanner.Scan() {
line := scanner.Text()
parts := strings.Split(line, " ")
parts = removeSpaces(parts)
for col, str := range parts {
entry := Entry{atoi(str), rows, col}
entries = append(entries, entry)
count++
}
rows++
}
fmt.Printf("Matrix dimensions: rows=%d, cols=%d\n", rows, count/rows)
sort.Sort(entries)
best := 0
for i := 0; i < 1000; i++ {
sum := run(entries, rows, count/rows)
if sum > best {
fmt.Printf("sum=%d, i=%d\n", sum, i)
best = sum
}
}
}
示例8: toString
func toString(scanner *bufio.Scanner) (string, error) {
output := ""
for scanner.Scan() {
output += scanner.Text() + "\n"
}
return output, scanner.Err()
}
示例9: readNextProblem
// Returns the relevant information for the next problem
//
// Each problem is described on two lines:
// 1. First line includes the number of barbers and the customer position
// 2. Second line has the cutting times for each barber
//
// Returns a tuple of (<all the barbers in a []Barber list, the customerNumber).
// These have all be converted into ints (instead of strings).
//
// Returns error when EOF is reached (ie: no more problems).
func readNextProblem(scanner *bufio.Scanner) ([]Barber, int, error) {
if !scanner.Scan() {
return nil, 0, errors.New("All done!")
}
firstLine := splitString(scanner.Text())
numBarbers := firstLine[0]
customerNumber := firstLine[1]
if !scanner.Scan() {
panic("EOF at unexpected time")
}
barberTimes := splitString(scanner.Text())
if len(barberTimes) != numBarbers {
log.Panicf("Found %d barbers, expected to find %d\n",
len(barberTimes), numBarbers)
}
barbers := make([]Barber, numBarbers)
for b, barberTime := range barberTimes {
// barberNumbers start at 1
barbers[b] = Barber{barberTime, b + 1}
}
return barbers, customerNumber, nil
}
示例10: pidForTid
func pidForTid(tid int) (pid int, err error) {
var (
status *os.File
scanner *bufio.Scanner
splits []string
)
status, err = os.Open(fmt.Sprintf("/proc/%d/status", tid))
if err != nil {
return
}
defer status.Close()
scanner = bufio.NewScanner(status)
for scanner.Scan() {
splits = strings.Split(scanner.Text(), ":")
if splits[0] != "Tgid" {
continue
}
pid, err = strconv.Atoi(strings.TrimSpace(splits[1]))
return
}
if err = scanner.Err(); err != nil {
return
}
err = fmt.Errorf("Pid not found for proc %d", tid)
return
}
示例11: runCommandsFromScanner
func runCommandsFromScanner(scanner *bufio.Scanner, action string) error {
lineNo := 0
for scanner.Scan() {
lineNo++
// create a new 'commandLine' for each input line,
// but always use same action for all lines
commandLine := NewAction(action, false)
// set executable name
newArgs := []string{os.Args[0]}
newArgs = append(newArgs, strings.Split(scanner.Text(), " ")...)
if err := commandLine.Parse(newArgs); err != nil {
return errors.New(fmt.Sprintf("%s: error at line %d: %s", commandLine.Action, lineNo, err))
}
err := commandLine.ExecuteAddAction()
if err != nil {
return errors.New(fmt.Sprintf("[file] %s: %s", commandLine.Action, err))
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
示例12: ProcessChanges
/*
ProcessChanges takes `git status -z` output and returns all status items.
(Note: in our case, we actually use `git status -bz` and remove branch header
when we process it earlier, but the results are binary identical.)
This is a complicated process because the format is weird. Each line is a
variable length number of columns (2-3), but the separator for 1-2 is a space
(but the content of columns can contain spaces too!), and the seperator for 2-3
is a NUL character (ASCII 0), *if* there is a third column. But here's where it
gets wacky: NUL is also the entry terminator (rather than a LF like in normal
porcelain mode)
Thankfully(?), column 1 which contains the status codes is a fixed length of two
bytes, and in theory the status codes contain enough secrets for us to determine
whether we should expect 2 or 3 columns (current hypothesis is we only get the
third column which is PATH2 when there is a "rename" operation). Sooo... we can
just read those two bytes and use that to determine how many NULs to scan to
until we have consumed a full entry.
We put up with this because it means no shell escaping, which should mean better
cross-platform support. Better hope some Windows people end up using it someday!
*/
func ProcessChanges(s *bufio.Scanner, root string) (results []*StatusItem) {
// Before we process any changes, get the Current Working Directory.
// We're going to need use to calculate absolute and relative filepaths for
// every change, so we get it once now and pass it along.
// If for some reason this fails (?), fallback to the git worktree root.
wd, err := os.Getwd()
if err != nil {
wd = root
}
for s.Scan() {
chunk := s.Bytes()
// ...if chunk represents a rename or copy op, need to append another chunk
// to get the full change item, with NUL manually reinserted because scanner
// will extract past it.
if (chunk[0] == 'R' || chunk[0] == 'C') && s.Scan() {
chunk = append(chunk, '\x00')
chunk = append(chunk, s.Bytes()...)
}
results = append(results, processChange(chunk, wd, root)...)
}
return
}
示例13: scanBlock
func scanBlock(scanner *bufio.Scanner) (*pfs.BlockRef, []byte, error) {
var buffer bytes.Buffer
var bytesWritten int
hash := newHash()
for scanner.Scan() {
// they take out the newline, put it back
bytes := append(scanner.Bytes(), '\n')
buffer.Write(bytes)
hash.Write(bytes)
bytesWritten += len(bytes)
if bytesWritten > blockSize {
break
}
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return &pfs.BlockRef{
Block: getBlock(hash),
Range: &pfs.ByteRange{
Lower: 0,
Upper: uint64(buffer.Len()),
},
}, buffer.Bytes(), nil
}
示例14: buildBoard
// buildBoard builds a "board" (an array) by scanning input, splitting comma-
// separated integers and inserting them into an array.
func buildBoard(input *bufio.Scanner, board *[81]int) {
l := 0
for input.Scan() {
for i, n := range strings.Split(input.Text(), ",") {
var val int
// If i is a dash, val is 0
if n == "-" {
val = 0
} else {
// Convert i to an int
val2, err := strconv.Atoi(n)
if err != nil {
fmt.Println(os.Stderr, err)
os.Exit(2)
}
val = val2
}
board[i+9*l] = val
}
l++
}
}
示例15: parseHeader
// parseHeader parses the first two lines of a block described in
// ParseFilelist docs. So it returns a data kind (files, symlinks or
// dirs) and a count of elements in the following list. If the
// returned kind is empty then it means that there is no more entries
// (provided that there is no error either).
func parseHeader(scanner *bufio.Scanner) (string, int, error) {
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return "", 0, err
}
// no more entries in the file, just return empty kind
return "", 0, nil
}
kind := scanner.Text()
if kind == "" {
return "", 0, fmt.Errorf("got an empty kind, expected 'files', 'symlinks' or 'dirs'")
}
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return "", 0, err
} else {
return "", 0, fmt.Errorf("expected a line with a count, unexpected EOF?")
}
}
countReader := strings.NewReader(scanner.Text())
count := 0
n, err := fmt.Fscanf(countReader, "(%d)", &count)
if err != nil {
return "", 0, err
}
if n != 1 {
return "", 0, fmt.Errorf("incorrectly formatted line with number of %s", kind)
}
return kind, count, nil
}