151

在golang里面正确读取一行

 5 years ago
source link: https://studygolang.com/articles/18807?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在golang读取一行的方法,发现网上很多童鞋都用错了(随便搜搜超过一半都是错的)。下面会演示正确的做法,心急的童鞋可以直接到最下面看正确代码

错误的用法1

func errorReadLine1(r io.Reader) {

    br := bufio.NewReader(r)

    for{

        l,e := br.ReadBytes('\n')

        if e == io.EOF{

            break

        }

        os.Stdout.Write(l)

    }

}

错误的用法2

func errorReadLine2(r io.Reader) {

    br := bufio.NewReader(r)

    for{

        l,e := br.ReadBytes('\n')

        if e != nil {

            break

        }

        os.Stdout.Write(l)

    }

}

构造一个数据让错误代码现出原形

sr := strings.NewReader("123\n456")

//输出了
//start run errorReadLine1
//123
fmt.Printf("start run errorReadLine1\n")

errorReadLine1(sr)

sr.Seek(0,0)

//输出了
//start run errorReadLine2
//123
fmt.Printf("start run errorReadLine2\n")

errorReadLine2(sr)

sr.Seek(0,0)

//输出了
//start run readLine
//123
//456
fmt.Printf("start run readLine\n")

readLine(sr)

九九八十一难,正确的用法是

func readLine(rio.Reader) {

    br := bufio.NewReader(r)

    for{

        l,e := br.ReadBytes('\n')

        if e != nil && len(l) == 0 {

            break

        }

        os.Stdout.Write(l)

    }

}

github代码示例 readline

挖坑过程,用go实现linux cat命令时发现。有兴趣的童鞋可以移步至 coreuitls 看下,现在已经完成了13个linux命令,未来会更多


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK