Golang : File system scanning
Problem :
How to scan all the files located inside a root directory in Golang?
Solution :
Use the filepath.Walk
function. See codes below :
package main
import (
"fmt"
"os"
"path/filepath"
)
func scan(path string, f os.FileInfo, err error) error {
fmt.Printf("Scanned %s with size %d bytes\n", path, f.Size())
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("USAGE : %s <target_directory> \n", os.Args[0])
os.Exit(0)
}
dir := os.Args[1] // 1st argument is the directory location
err := filepath.Walk(dir, scan)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Sample output :
./scanfilesystem /Users/
Scanned /Users/ with size 170 bytes
Scanned /Users/.localized with size 0 bytes
Scanned /Users/Shared with size 136 bytes
Scanned /Users/Shared/.localized with size 0 bytes
Scanned /Users/Shared/SC Info with size 68 bytes
Scanned /Users/sweetlogic with size 8194 bytes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11k Golang : Get month name from date example
+5.2k Golang : Experimental emojis or emoticons icons programming language
+13.7k Golang : Basic authentication with .htpasswd file
+13.1k Golang : Find network of an IP address
+10k Golang : How to pipe input data to executing child process?
+9.1k Golang : Get login name from environment and prompt for password
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+45.4k Golang : Convert int to byte array([]byte)
+17k Golang : Implement getters and setters
+14.9k Golang : Get file permission
+6.8k Golang : get the current working directory of a running program
+14.3k Golang : How to convert(cast) IP address to string?