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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵