doulu7921 2012-05-24 22:28
浏览 51
已采纳

使用Go编程语言读取和使用外部文件

I have been learning the Go programming language by doing some of the Project Euler problems. I am now on [problem 13] (http://projecteuler.net/problem=13). It contains an external file with 100 lines of 50 digit numbers. My question is: How can this file be read into a Go program and worked with? Does Go have a readlines function? I've read about the io and ioutil packages, and about all I can come up with is reading in the file and printing it; however, I am not sure how to work with the file... Can it be assigned to a variable? Is there a readlines function, etc...

Any help would be appreaciated.

Here is what I have so far:

package main

import "fmt"
import "io/ioutil"

func main() {
        fmt.Println(ioutil.ReadFile("one-hundred_50.txt"))
}
  • 写回答

3条回答 默认 最新

  • dsadsa123111 2012-05-24 23:28
    关注

    There are ways to read a file line by line (and there are examples if you search here on SO) but really ioutil.ReadFile is a good start there. Sure you can assign it to a variable. Look at the function signature for ReadFile and see how it returns both a byte slice and an error. Assign both; check that the error is nil. Print the error if it's not nil so you can see what's wrong. Then once you have the bytes in a variable, try spitting it up by lines. Try bytes.Split, or easier, convert it to a string and use strings.Split.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?