How to get latest file from folder

I need latest file from subfolder. I have used os.readdir

Which is very fast ,but it is not giving me full file path…

How to achieve this.

Use filepath package, for example:

import (
    "fmt"
    "os"
    "path/filepath"
)

files, _ = os.ReadDir(dir)
path, _ := filepath.Abs(dir)
for _, file := range files {
    fmt.Println(filepath.Join(path, file.Name())
}
1 Like

try this one:

type FileInfo struct {
    os.FileInfo
    FullPath string
}

func GetLatestFileInDir(dir string) (*FileInfo, error) {
	var files []FileInfo

	err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			files = append(files, FileInfo{FileInfo: info, FullPath: path})
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	if len(files) == 0 {
		return nil, fmt.Errorf("no files found in directory %s", dir)
	}

	// Sort files by modification time
	sort.Slice(files, func(i, j int) bool {
		return files[i].ModTime().After(files[j].ModTime())
	})

	// Return the latest file
	return &files[0], nil
}

Thank.

I have tried filepath.walk it is slow compre to readdir

I will check again