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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记