Reading and working with an external file in the Go programming language

I am learning the Go programming language, performing some of the problems of Project Euler. I am now on [issue 13] ( http://projecteuler.net/problem=13 ). It contains an external file with 100 lines of 50 digits. My question is: how can this file be read in the Go program and work with it? Is there a read function? I read about io and ioutil packages, and all I can think of is reading in a file and printing it; however, I'm not sure how to work with the file ... Can it be assigned to a variable? There is a readlines function, etc.

Any help would be appreciated.

Here is what I still have:

package main import "fmt" import "io/ioutil" func main() { fmt.Println(ioutil.ReadFile("one-hundred_50.txt")) } 
+4
source share
3 answers

There are ways to read the file line by line (and there are examples if you are looking here on SO), but actually ioutil.ReadFile is a good start. Of course, 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; make sure the error is zero. Print the error if it is not zero so that you can see what is wrong. Then, as soon as you have bytes in the variable, try to spit along the lines. Try bytes.Split or simpler, convert it to a string and use string.Split.

+3
source

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

For this Euler problem, you can simply 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') } } 

For use:

 go run solution.go < inputfile 
+1
source

Since this question was asked and answered, the bufio package was updated (for Go 1.1), and perhaps a more pleasant solution is now available (not that it was all bad).

The Scanner type from the bufio package makes this very simple:

 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 } } 
0
source

Source: https://habr.com/ru/post/1414266/


All Articles