Go Package os: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(26 intermediate revisions by the same user not shown)
Line 3: Line 3:


=Internal=
=Internal=
* [[File Operations in Go#Overview|File Operations in Go]]
* [[Go_Language_Modularization#os|Standard library]]
* [[Go_Language_Modularization#os|Standard library]]
* [[File Operations in Go#Overview|File Operations in Go]]


=Overview=
=Overview=
Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error.
=Accessing Environment Variables in Go=
To pull the value of an environment variable and also get an indication whether the environment variable is set to "" but is still defined, use:
<syntaxhighlight lang='go'>
value, ok := os.LookupEnv("SOME_ENV_VAR")
</syntaxhighlight>
<code>ok</code> is set to <code>false</code> if the environment variable has not been defined.
Note that:
<syntaxhighlight lang='bash'>
export SOME_ENV_VAR
</syntaxhighlight>
does not define a variable, unless a value, including empty string is provided. In this case <code>os.LookupEnv()</code> will return <code>false</code>.
<code>ok</code> is set to <code>true</code> if the environment variable has been defined, even with an empty string value.
<syntaxhighlight lang='bash'>
export SOME_ENV_VAR=""
</syntaxhighlight>
makes <code>os.LookupEnv()</code> return <code>""</code>, <code>true</code>.
=<tt>os.File</tt>=
{{External|https://pkg.go.dev/os#File}}
<code>File</code> represents an open file descriptor. An existing file can be opened with <code>[[#os.Open()|os.Open()]]</code>. A new file can be created with <code>[[#os.Create()|os.Create()]]</code>.
==<tt>os.File.Stat()</tt>==
To introspect the state of the file, <code>File.Stat()</code> is available. The function the <code>FileInfo</code> structure describing the file. If there is an error, it will be of type <code>*PathError</code>.
<syntaxhighlight lang='go'>
f := os.Stdout
fi, err := f.Stat()
if err != nil {
  ...
}
fmt.Printf("Name: %s\n", fi.Name())
fmt.Printf("Size: %d\n", fi.Size())
fmt.Printf("Mode: %v\n", fi.Mode())
fmt.Printf("ModTime: %v\n", fi.ModTime())
fmt.Printf("IsDir: %v\n", fi.IsDir())
fmt.Printf("Sys: %v\n", fi.Sys())
</syntaxhighlight>


=Reading and Writing an Entire File in/from Memory=
=Reading and Writing an Entire File in/from Memory=
Line 26: Line 68:
=Sequentially Reading and Writing Byte Arrays=
=Sequentially Reading and Writing Byte Arrays=
==Reading==
==Reading==
===<tt>os.Open()</tt>===
{{External|https://golang.org/pkg/os/#Open}}
Open the file with <code>os.Open()</code> and then use the <code>File</code> <code>Read()</code> method to read into a byte slice.
Open the file with <code>os.Open()</code> and then use the <code>File</code> <code>Read()</code> method to read into a byte slice.
If the file does not exist, it returns a <code>fs.PathError</code>.
<font color=darkkhaki>Works with files and directories.</font>
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
bs := make([]byte, 10)
bs := make([]byte, 10)
Line 32: Line 81:
if err != nil {
if err != nil {
   // ...
   // ...
  f.Close()
   return
   return
}
}
defer f.Close()
for {
for {
   cnt, err := f.Read(bs)
   cnt, err := f.Read(bs)
Line 48: Line 97:


==Writing==
==Writing==
Open the file with <code>os.Create()</code> and then use the <code>File</code> <code>Write()</code> method write the content of a byte slice, or <code>WriteString()</code> to write strings. The file must be explicitly closed after use with <code>Close()</code>:
===<tt>os.Create()</tt>===
{{External|https://golang.org/pkg/os/#Create}}
Open the file with <code>os.Create()</code>.  It will return a <code>os.File</code> that implements <code>[[Go_Package_io#Reader|io.Reader]]</code>, <code>[[Go_Package_io#Writer|io.Writer]]</code> and <code>[[Go_Package_io#Closer|io.Closer]]</code> interfaces.
 
Then use the <code>File</code> <code>Write()</code> method write the content of a byte slice, or <code>WriteString()</code> to write strings. The file must be explicitly closed after use with <code>Close()</code>:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
var err error
var err error
Line 76: Line 129:


<font color=darkkhaki>What happens if open the file with <code>os.Open()</code> and then I write?</font>
<font color=darkkhaki>What happens if open the file with <code>os.Open()</code> and then I write?</font>
==Close==
=Local Filesystem Interaction=
==<tt>os.Getwd()</tt>==
Return a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths due to symbolic links, <code>Getwd()</code> may return any one of them.
==Checking whether a File Exists==
<syntaxhighlight lang='go'>
_, err := os.Stat("/path/to/whatever")
if os.IsNotExist(err) {
  // file does not exist
}
</syntaxhighlight>
==Removing (Deleting) a File==
{{External|https://pkg.go.dev/os#Remove}}
<syntaxhighlight lang='go'>
os.Remove()
</syntaxhighlight>


=TO DEPLETE=
=TO DEPLETE=
<font color=darkkhaki>
<font color=darkkhaki>
==Functions==
==Functions==
===<tt>os.Open()</tt>===
* https://golang.org/pkg/os/#Open
Works with files and directories.
===<tt>os.Create()</tt>===
* https://golang.org/pkg/os/#Create
==<tt>os.File</tt>==
* https://golang.org/pkg/os/#File
===<tt>os.File</tt> Methods===
* <tt>[https://golang.org/pkg/os/#File.Stat File.Stat()]</tt>
* <tt>[https://golang.org/pkg/os/#File.Read File.Read()]</tt>
* <tt>[https://golang.org/pkg/os/#File.Close File.Close()]</tt>
* <tt>[https://golang.org/pkg/os/#File.Readdir File.Readdir()]</tt>


==<tt>FileInfo</tt>==
==<tt>FileInfo</tt>==

Latest revision as of 23:49, 8 August 2024

External

Internal

Overview

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error.

Accessing Environment Variables in Go

To pull the value of an environment variable and also get an indication whether the environment variable is set to "" but is still defined, use:

value, ok := os.LookupEnv("SOME_ENV_VAR")

ok is set to false if the environment variable has not been defined.

Note that:

export SOME_ENV_VAR

does not define a variable, unless a value, including empty string is provided. In this case os.LookupEnv() will return false.

ok is set to true if the environment variable has been defined, even with an empty string value.

export SOME_ENV_VAR=""

makes os.LookupEnv() return "", true.

os.File

https://pkg.go.dev/os#File

File represents an open file descriptor. An existing file can be opened with os.Open(). A new file can be created with os.Create().

os.File.Stat()

To introspect the state of the file, File.Stat() is available. The function the FileInfo structure describing the file. If there is an error, it will be of type *PathError.

f := os.Stdout
fi, err := f.Stat()
if err != nil {
   ...
}
fmt.Printf("Name: %s\n", fi.Name())
fmt.Printf("Size: %d\n", fi.Size())
fmt.Printf("Mode: %v\n", fi.Mode())
fmt.Printf("ModTime: %v\n", fi.ModTime())
fmt.Printf("IsDir: %v\n", fi.IsDir())
fmt.Printf("Sys: %v\n", fi.Sys())

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

Reading

os.Open()

https://golang.org/pkg/os/#Open

Open the file with os.Open() and then use the File Read() method to read into a byte slice.

If the file does not exist, it returns a fs.PathError.

Works with files and directories.

bs := make([]byte, 10)
f, err := os.Open("/Users/ovidiu/tmp/test.txt")
if err != nil {
  // ...
  return
}
defer f.Close()
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 with Close().

Writing

os.Create()

https://golang.org/pkg/os/#Create

Open the file with os.Create(). It will return a os.File that implements io.Reader, io.Writer and io.Closer interfaces.

Then use the File Write() method write the content of a byte slice, or WriteString() to write strings. The file must be explicitly closed after use with Close():

var err error
f, err := os.Create("/Users/ovidiu/tmp/test3.txt")
if err != nil {
 // ...
}
_, err = f.WriteString("This is the first line\n")
if err != nil {
  // ...
}
_, err = f.WriteString("This is the second line\n")
if err != nil {
  // ...
}
err = f.Close()
if err != nil {
  // ...
}

The file content will be:

This is the first line
This is the second line

What happens if open the file with os.Open() and then I write?

Close

Local Filesystem Interaction

os.Getwd()

Return a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths due to symbolic links, Getwd() may return any one of them.

Checking whether a File Exists

_, err := os.Stat("/path/to/whatever")
if os.IsNotExist(err) {
  // file does not exist
}

Removing (Deleting) a File

https://pkg.go.dev/os#Remove
os.Remove()

TO DEPLETE

Functions

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:

Command Line Parsing