Skip to content
Golang Developer tips

See More. Do More…

  • Home
  • Privacy Policy
  • Contact
  • About us

Post navigation

← Previous
Next →

Read file info in Golang

January 16, 2022
2 Comments
mel182
Security
read file metadata

In this article, we are going to show you how to read files or directory info in Golang. When it comes to security it is very important to determine who is the owner, last changed, and if the file contains hidden files. Hackers nowadays are notorious for leaving malicious files that can affect your computer.

In order to read the file, we need to use the os.Stat() function which returns the file metadata. Such information is provided through a FileInfo struct. 

fileInfo, err := os.Stat("./golang/file_info/english/file_directory/file.txt")
if err != nil {
   log.Fatal(err)
}

From the FileInfo struct all additional file properties can be extracted. The Name() function returns the file name.

fmt.Println("File name:     ", fileInfo.Name())

The Size() returns the file size in bytes. To make it much easier to read in our example, we create an additional function that returns the file size in a string format. It expects a FileInfo struct and calculate the size and returns it in bytes, kilobytes, or megabytes (depends on the calculation).

func getFileSize(fileInfo fs.FileInfo) string {

   size := fileInfo.Size()
   if size < 1000 { // File is in bytes
      return fmt.Sprintf("%d bytes", size)
   } else { // else file size is in kilobytes or megabytes
      fileSizeInKb := float64(size) / float64(1000)
      if fileSizeInKb > 1000 { // file size is in megabytes
         fileSizeInMb := fileSizeInKb / float64(1000)
         return fmt.Sprintf("%d Mb", fileSizeInMb)
      } else { // file size is in kilobytes
         return fmt.Sprintf("%d Kb", fileSizeInKb)
      }
   }
}

To determine the file permission, the Mode() function can be used. The function returns a FileMode struct that represents a file’s mode and permission bits. Not all bits are applied to all Operating systems.

fmt.Println("Permissions:   ", directoryInfo.Mode())

For the last modification metadata, the ModTime() can be used that returns a Time struct.

fmt.Println("Last modified: ", directoryInfo.ModTime())

In addition to the getFileSize function, another one is created to determine if a file is a directory. It returns the yes or no string.

func isDirectory(fileInfo fs.FileInfo) string {
   var result = "No"
   if fileInfo.IsDir() {
      result = "yes"
   }
   return result
}
fmt.Println("|----------- File info -----------|")
fmt.Println("File name:     ", fileInfo.Name())
fmt.Println("Size:          ", getFileSize(fileInfo))
fmt.Println("Permissions:   ", fileInfo.Mode())
fmt.Println("Last modified: ", fileInfo.ModTime())
fmt.Println("Is Directory:  ", isDirectory(fileInfo))
fmt.Println("|----------- File info -----------|\n")

The code snippet shows a directory example.

directoryInfo, err := os.Stat("./golang/file_info/english/file_directory")
if err != nil {
   log.Fatal(err)
}
fmt.Println("|----------- Directory info -----------|")
fmt.Println("File name:     ", directoryInfo.Name())
fmt.Println("Size:          ", getFileSize(directoryInfo))
fmt.Println("Permissions:   ", directoryInfo.Mode())
fmt.Println("Last modified: ", directoryInfo.ModTime())
fmt.Println("Is Directory:  ", isDirectory(directoryInfo))
fmt.Println("|----------- Directory info -----------|")

Program result:

|----------- File info -----------|
File name:      file.txt
Size:           21 bytes
Permissions:    -rw-r--r--
Last modified:  2022-01-09 17:26:32.81671206 -0400 AST
Is Directory:   No
|----------- File info -----------|

|----------- Directory info -----------|
File name:      file_directory
Size:           96 bytes
Permissions:    drwxr-xr-x
Last modified:  2022-01-09 17:42:13.997886317 -0400 AST
Is Directory:   yes
|----------- Directory info -----------|

Visit our GitHub repository for the project source code and clone our repository for all future projects.

Follow us:

2 replies on “Read file info in Golang”

  1. israelnightclub.com on April 2, 2022
    Reply ↓

    Im very happy to find this web site. I want to to thank you for ones time just for this fantastic read!! I definitely appreciated every part of it and i also have you saved as a favorite to see new information in your blog.

  2. https://israel-lady.co.il on August 11, 2022
    Reply ↓

    Good post. I learn something new and challenging on sites I stumbleupon on a daily basis. Its always helpful to read through content from other authors and practice a little something from other web sites.

Leave a Reply Cancel reply

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

Recent Posts

  • Add random noise to an image in Go
  • Handy script when using Go module in GoLand
  • Read file info in Golang
  • Generate QR code with data in Golang
  • Building a lightweight high-performance RESTful API using HTTP router in Go

Recent Comments

  • magicwiring.com on Go IDE in Windows
  • https://israel-lady.co.il on Read file info in Golang
  • Haiva on Go IDE in Windows
  • Haunk on Go IDE in Windows
  • Juanita on Go IDE in Windows

Archives

  • May 2022
  • April 2022
  • January 2022
  • October 2021
  • September 2021
  • August 2021
  • May 2020
  • April 2020
  • March 2020
  • January 2020

Categories

  • Go features
  • macOS
  • Ubuntu (linux)
  • Windows

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
Golang Developer tips © 2023. All Rights Reserved.
Proudly powered by WordPress
A theme by Sampression