How to read/write from/to file using Go?

前端 未结 8 1052
慢半拍i
慢半拍i 2020-11-28 17:23

I\'ve been trying to learn Go on my own, but I\'ve been stumped on trying read from and write to ordinary files.

I can get as far as inFile, _ := os.Open(INFIL

8条回答
  •  抹茶落季
    2020-11-28 17:48

    The Read method takes a byte parameter because that is the buffer it will read into. It's a common Idiom in some circles and makes some sense when you think about it.

    This way you can determine how many bytes will be read by the reader and inspect the return to see how many bytes actually were read and handle any errors appropriately.

    As others have pointed in their answers bufio is probably what you want for reading from most files.

    I'll add one other hint since it's really useful. Reading a line from a file is best accomplished not by the ReadLine method but the ReadBytes or ReadString method instead.

提交回复
热议问题