doujian1954 2013-09-18 00:33
浏览 25

程序仅输出输入文件的最后一个字符串

i am trying to create a simple program to read lines from a text file and print them out to the console in golang. I spent lots of time going over my code and I simply can't understand why only the last line is being printed out to the screen. can anyone tell me where I am going wrong here? Everything here should compile and run.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func Readln(r *bufio.Reader) (string, error) {
    var (
        isPrefix bool  = true
        err      error = nil
        line, ln []byte
    )
    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }
    return string(ln), err
}

func main() {
    f, err := os.Open("tickers.txt")
    if err != nil {
        fmt.Printf("error opening file: %v
", err)
        os.Exit(1)
    }
    r := bufio.NewReader(f)
    s, e := Readln(r)
    for e == nil {
        fmt.Println(s)
        s, e = Readln(r)
    }
}
  • 写回答

1条回答 默认 最新

  • drex88669 2013-09-18 01:14
    关注

    I therefore suspect that the problem is in your tickers.txt file line endings. The docs for ReadLine() also indicate that for most situations a Scanner is more suitable.

    The following SO question has some useful information for alternative implementations: reading file line by line in go

    I then used the example in the above question to re-implement your main function as follows:

    f, err := os.Open("tickers.txt")
    if err != nil {
        fmt.Printf("error opening file: %v
    ", err)
        os.Exit(1)
    }
    
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    
    if err := scanner.Err(); err != nil {
        fmt.Println(err)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度