Go Package os: Difference between revisions
Jump to navigation
Jump to search
Line 25: | Line 25: | ||
=Sequentially Reading and Writing Byte Arrays= | =Sequentially Reading and Writing Byte Arrays= | ||
<font color=darkkhaki>Move to [[File Operations in Go]].</font> | |||
==Reading== | ==Reading== | ||
Open the file with <code>os.Open()</code> and then use [[Go Package file#Overview|<tt>file</tt> package]] <code>file.Read()</code> to read into a byte slice. | Open the file with <code>os.Open()</code> and then use [[Go Package file#Overview|<tt>file</tt> package]] <code>file.Read()</code> to read into a byte slice. |
Revision as of 18:46, 25 August 2023
External
Internal
Overview
Reading and Writing an Entire File in/from Memory
Read with ReadFile()
To read the content of an entire file into a byte slice:
bs, err := os.ReadFile("/Users/ovidiu/tmp/test.txt")
os.ReadFile()
closes the file after use.
Write with WriteFile()
To write in-memory data into a file:
s := "This\nis multi-line\nfile\ncontent\n"
err := os.WriteFile("/Users/ovidiu/tmp/test2.txt", []byte(s), 0777)
os.WriteFile()
closes the file after use.
Sequentially Reading and Writing Byte Arrays
Move to File Operations in Go.
Reading
Open the file with os.Open()
and then use file package file.Read()
to read into a byte slice.
bs := make([]byte, 10)
f, err := os.Open("/Users/ovidiu/tmp/test.txt")
if err != nil {
// ...
f.Close()
return
}
for {
cnt, err := f.Read(bs)
if err != nil {
fmt.Println(err)
f.Close()
return
}
fmt.Println("read ", cnt, " bytes")
}
The file must be explicitly closed after use.
Writing
To write in-memory data into a file:
s := "This\nis multi-line\nfile\ncontent\n"
err := os.WriteFile("/Users/ovidiu/tmp/test2.txt", []byte(s), 0777)
The file must be explicitly closed after use.
TO DEPLETE
Functions
os.Open()
Works with files and directories.
os.Create()
os.File
os.File Methods
FileInfo
FileInfo Methods
- Size()
os.Args
os.Args is a string slice that holds the command-line arguments, starting with the program name. For more details on how to use see: