What is os.Lstat() Function in Golang

The os.Lstat() is a built-in Golang function to get information about a symbolic link. It accepts the name as an argument and returns the fileinfo struct.

The os.Lstat() function is helpful when you want to check if a file is a symbolic link and get information about the link.

The main difference between os.Lstat() and os.Stat() function is that os.Lstat() function follows symbolic links and returns information about the symbolic link, while the os.Stat() function follows symbolic links and returns information about the file the link points to.

Syntax

func Lstat(name string) (FileInfo, error)

Parameters

The name is the name of the file or directory for which you want to get the information. 

Return value

The Lstat() function returns a FileInfo struct, which contains information about the file or directory, such as its size, mode, and modification time. If there is an error, the function returns an error value.

Example

In my current working directory, I have created an app.txt file.

package main

import (
  "fmt"
  "os"
)

func main() {
  fileInfo, err := os.Lstat("app.txt")
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(fileInfo)
}

Output

&{app.txt 0 420 {528096986 63811822410 0x102350580} 
{16777232 33188 1 36339649 501 20 0 [0 0 0 0] {1676225610 528096986} 
{1676225610 528096986} {1676225610 528096986} {1676225610 528096986} 0 0 4096 0 0 0 [0 0]}}

In this example, the os.Lstat() function is used to get information about the file “app.txt”.

If there is no error, the function returns a FileInfo struct, which can be printed using the fmt.Println() function.

The FileInfo structure returned by os.Lstat() contains information such as the file’s size, permissions, modification time, and type (whether it’s a regular file, directory, symbolic link, etc.).

This information can be used to check how to interact with the file or to display information about it to the user.

Summary

The os.Lstat() function gives Go programs information about directory listings, file management, and file and their properties, including symbolic links.

Leave a Comment