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.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *