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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?