4

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Check out bufio. This answer uses it to read the entire file into memory.

For this Euler problem you can just use ReadString:

package main

import (
  "os"
  "bufio"
  "fmt"
)

func main() {
  r := bufio.NewReader(os.Stdin)
  line, err := r.ReadString('\n')
  for i := 1; err == nil; i++ {
    fmt.Printf("Line %d: %s", i, line)
    line, err = r.ReadString('\n')
  }
}

To use:

go run solution.go < inputfile

Comments

0

Since this question was asked and answered the bufio package has been updated (for Go 1.1) and perhaps a nicer solution is now available (not that any of these are bad).

The Scanner type from the bufio package makes this really easy:

func main() {
    f, e := os.Open("one-hundred_50.txt")
    if e != nil {
        // error opening file, handle it
    }
    s := bufio.NewScanner(f)
    for s.Scan() {
        // scanner.Text() contains the current line
    }
    if e = s.Err(); e != nil {
        // error while scanning; no error at EOF
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.