Explain how you would read from a file in Go line by line.
- Use the ioutil.ReadFile function to read the entire file into memory at once and then split it into lines.
- Use the os.Open function to open the file, create a Scanner to read line by line, and loop through the file.
- Use the fmt.Scanln function to read lines from the file one by one.
- Use the bufio.NewReader function to create a buffered reader for the file and then use the ReadString method to read lines.
In Go, to read from a file line by line, you typically use the os.Open function to open the file, creating a *os.File object. Then, you create a Scanner using bufio.NewScanner(file) and use a loop to iterate over the lines using the scanner.Scan() method. This method reads one line at a time, and you can access the text of the line using scanner.Text(). This approach is memory-efficient as it doesn't load the entire file into memory.
Loading...
Related Quiz
- Explain how Goroutines can be used to implement a worker pool pattern.
- Discuss how you would design a centralized error handling mechanism in a Go application.
- _____ is a common Go library used to create RESTful APIs.
- The defer statement is used to ensure that a function call is performed _____ in a function.
- How would you use build tags in Go?