github.com/searKing/golang/go@v1.2.117/os/dir.go (about)

     1  // Copyright 2023 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package os
     6  
     7  import (
     8  	"os"
     9  	"sort"
    10  )
    11  
    12  // ReadDirN reads the named directory,
    13  // returning a slice of its directory entries sorted by filename.
    14  // If an error occurs reading the directory,
    15  // ReadDirN returns a slice of entries it was able to read before the error,
    16  // along with the error.
    17  //
    18  // If n > 0, ReadDirN returns at most n DirEntry records.
    19  // In this case, if ReadDirN returns an empty slice, it will return an error explaining why.
    20  // At the end of a directory, the error is [io.EOF].
    21  //
    22  // If n <= 0, ReadDirN returns all the DirEntry records remaining in the directory.
    23  // When it succeeds, it returns a nil error (not [io.EOF]).
    24  // To read all dirs, see [os.ReadDir], or set n as -1.
    25  func ReadDirN(name string, n int) ([]os.DirEntry, error) {
    26  	f, err := os.Open(name)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	defer f.Close()
    31  
    32  	dirs, err := f.ReadDir(n)
    33  	if len(dirs) > 1 {
    34  		sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
    35  	}
    36  	return dirs, err
    37  }