Calculate Directory Size in Go: Efficiently Excluding Directories
This Go function calculateDirectorySize calculates the size of a directory by recursively traversing its contents. It accumulates the size of all regular files within the directory and excludes directories from the calculation.
func (srv *DataMigrateService) calculateDirectorySize(dirPath string) (int64, error) {
logger.Infof('calculate directory size start..., the param is dirPath:%s', dirPath)
var size int64
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
logger.Error(err.Error())
return err
}
if !info.IsDir() && info.Mode().IsRegular() {
size += info.Size()
}
return nil
})
if err != nil {
logger.Error(err.Error())
return 0, err
}
return size, nil
}
This code effectively calculates the total size of all files within a given directory. It utilizes filepath.Walk to traverse the directory structure, checking if each entry is a regular file using info.IsDir() and info.Mode().IsRegular(). If it's a regular file, the code adds its size to the size variable. The code efficiently excludes directories from the calculation, ensuring that only file sizes are considered.
The code snippet also includes error handling, logging errors encountered during the directory traversal. It returns the total size of the directory and any error encountered during the process.
原文地址: https://www.cveoy.top/t/topic/fwfr 著作权归作者所有。请勿转载和采集!