10 examples of 'golang read file line by line' in Go

Every line of 'golang read file line by line' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
174func gokFileLineNum(file string, ln int) string {
175 f, err := ioutil.ReadFile(file)
176 if err != nil {
177 fmt.Println("gokFileLineNum Error => ",err)
178 return "0"
179 }
180 lines := strings.Split(string(f), "\n")
181 comment := lines[ln-2]
182 if len(comment) < 2 {
183 return "[unknown ln]"
184 }
185 return comment[2:]
186}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

31func getLinesInFile(filepath string) int {
32 file, err := os.Open(filepath)
33 defer file.Close()
34
35 if err != nil {
36 fmt.Println(err)
37 return 0
38 }
39
40 fscanner := bufio.NewScanner(file)
41 count := 0
42 for fscanner.Scan() {
43 count++
44 }
45
46 return count
47}
80func ReadLineByNumber(filePath string, lineNumber int) (string, error) {
81 f, err := OpenFile(filePath)
82 if err != nil {
83 return "", err
84 }
85
86 scanner := bufio.NewScanner(f)
87 line := ""
88 for i := 1; scanner.Scan(); i++ {
89 if i == lineNumber {
90 line = scanner.Text()
91 break
92 }
93 }
94
95 err = f.Close()
96 if err != nil {
97 return "", err
98 }
99 return line, err
100}
15func readLines(filePath string) (lines []string, err error) {
16 file, err := os.Open(filePath)
17 if err != nil {
18 msg := fmt.Sprintf("file %s doesn't exist, please run `lab sync` first", filePath)
19 utils.Err(msg)
20 }
21 defer file.Close()
22 buffer := bufio.NewReader(file)
23 for {
24 value, _, err := buffer.ReadLine()
25 if err == io.EOF {
26 break
27 }
28 lines = append(lines, string(value))
29 }
30 return lines, err
31}
32func getLines(inFile io.Reader) []string {
33
34 lines := make([]string, 0, 10)
35 bufferedReader := bufio.NewReader(inFile)
36 line, err := readLine(bufferedReader)
37 for err == nil {
38 lines = append(lines, line)
39 line, err = readLine(bufferedReader)
40 }
41
42 return lines
43}
10func main() {
11 // need to read the input.txt file and split each line into a slice
12 input := util.ReadFile("../input.txt")
13 stringSlice := strings.Split(input, "\n")
14
15 // split into a 2D grid with each character
16 gridSlice := make([][]string, len(stringSlice))
17 for i, str := range stringSlice {
18 gridSlice[i] = strings.Split(str, "")
19 }
20
21 // will be the final result value
22 var result int
23 var finalCoords [2]int
24 // iterate through entire slice, for each asteroid found, call a helper function
25 for rowIndex, rowSlice := range gridSlice {
26 for colIndex, element := range rowSlice {
27 if element == "#" {
28 // # are "asteroids", . are empty space
29 // helper function will return how many asteroids are "findable" from the current asteroid
30 visibleFromElement := visibleFromAsteroid(gridSlice, rowIndex, colIndex)
31
32 // take max of return of helper function at end of each loop
33 if result < visibleFromElement {
34 result = visibleFromElement
35 finalCoords[0], finalCoords[1] = rowIndex, colIndex
36 }
37 }
38 }
39 }
40
41 // print out the max found
42 fmt.Printf("best asteroid for the station: row[%v] col[%v]\n", finalCoords[0], finalCoords[1]) // [13, 11]
43 fmt.Println("from 13, 11 (y, x)", result)
44}
10func main() {
11 input := util.ReadFile("../input.txt")
12
13 lines := strings.Split(input, "\n")
14
15 grid := make([][]string, len(lines))
16 for i, v := range lines {
17 grid[i] = strings.Split(v, "")
18 }
19
20 // can map biodiversity scores because they're essentially bitmaps
21 previousBiodiversities := map[int]bool{getBiodiversity(grid): true}
22
23 // run indefinitely
24 for {
25 // step through a minute
26 grid = stepMinute(grid)
27 newBiodiversity := getBiodiversity(grid)
28
29 // if new biodiversity score is already in the map, print it and exit
30 if previousBiodiversities[newBiodiversity] {
31 fmt.Println("Repeated biodiversity score", newBiodiversity)
32 return
33 }
34
35 // set biodiversity score into in map
36 previousBiodiversities[newBiodiversity] = true
37 }
38}
11func ReadLines(filename string) ([]string, error) {
12 f, err := os.OpenFile(filename, os.O_RDONLY, 0400)
13 if err != nil {
14 return []string{""}, err
15 }
16 defer f.Close()
17
18 var ret []string
19
20 r := bufio.NewReader(f)
21 for {
22 line, err := r.ReadString('\n')
23 if err != nil {
24 break
25 }
26 ret = append(ret, strings.Trim(line, "\n"))
27 }
28 return ret, nil
29}
214func Line(c *Context, s *Scope, line int) {
215 lineWithPrefix(c, s, line, "")
216}
170func readLine(r *bufio.Reader, lineBuf *[]byte) bool {
171 if !readBytesUntil(r, '\n', lineBuf) {
172 return false
173 }
174 line := *lineBuf
175 if len(line) == 0 {
176 return true
177 }
178 lastN := len(line) - 1
179 if line[lastN] == '\r' {
180 line = line[:lastN]
181 }
182 *lineBuf = line
183 return true
184}

Related snippets