Movatterモバイル変換


[0]ホーム

URL:


fs

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:8Imported by:41,598

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package fs defines basic interfaces to a file system.A file system can be provided by the host operating systembut also by other packages.

See thetesting/fstest package for support with testingimplementations of file systems.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (ErrInvalid    = errInvalid()// "invalid argument"ErrPermission = errPermission()// "permission denied"ErrExist      = errExist()// "file already exists"ErrNotExist   = errNotExist()// "file does not exist"ErrClosed     = errClosed()// "file already closed")

Generic file system errors.Errors returned by file systems can be tested against these errorsusingerrors.Is.

View Source
var SkipAll =errors.New("skip everything and stop the walk")

SkipAll is used as a return value fromWalkDirFunc to indicate thatall remaining files and directories are to be skipped. It is not returnedas an error by any function.

View Source
var SkipDir =errors.New("skip this directory")

SkipDir is used as a return value fromWalkDirFunc to indicate thatthe directory named in the call is to be skipped. It is not returnedas an error by any function.

Functions

funcFormatDirEntryadded ingo1.21.0

func FormatDirEntry(dirDirEntry)string

FormatDirEntry returns a formatted version of dir for human readability.Implementations ofDirEntry can call this from a String method.The outputs for a directory named subdir and a file named hello.go are:

d subdir/- hello.go

funcFormatFileInfoadded ingo1.21.0

func FormatFileInfo(infoFileInfo)string

FormatFileInfo returns a formatted version of info for human readability.Implementations ofFileInfo can call this from a String method.The output for a file named "hello.go", 100 bytes, mode 0o644, createdJanuary 1, 1970 at noon is

-rw-r--r-- 100 1970-01-01 12:00:00 hello.go

funcGlob

func Glob(fsysFS, patternstring) (matches []string, errerror)

Glob returns the names of all files matching pattern or nilif there is no matching file. The syntax of patterns is the sameas inpath.Match. The pattern may describe hierarchical names such asusr/*/bin/ed.

Glob ignores file system errors such as I/O errors reading directories.The only possible returned error ispath.ErrBadPattern, reporting thatthe pattern is malformed.

If fs implementsGlobFS, Glob calls fs.Glob.Otherwise, Glob usesReadDir to traverse the directory treeand look for matches for the pattern.

Example
package mainimport ("fmt""io/fs""log""testing/fstest")func main() {fsys := fstest.MapFS{"file.txt":        {},"file.go":         {},"dir/file.txt":    {},"dir/file.go":     {},"dir/subdir/x.go": {},}patterns := []string{"*.txt","*.go","dir/*.go","dir/*/x.go",}for _, pattern := range patterns {matches, err := fs.Glob(fsys, pattern)if err != nil {log.Fatal(err)}fmt.Printf("%q matches: %v\n", pattern, matches)}}
Output:"*.txt" matches: [file.txt]"*.go" matches: [file.go]"dir/*.go" matches: [dir/file.go]"dir/*/x.go" matches: [dir/subdir/x.go]

funcReadFile

func ReadFile(fsysFS, namestring) ([]byte,error)

ReadFile reads the named file from the file system fs and returns its contents.A successful call returns a nil error, notio.EOF.(Because ReadFile reads the whole file, the expected EOFfrom the final Read is not treated as an error to be reported.)

If fs implementsReadFileFS, ReadFile calls fs.ReadFile.Otherwise ReadFile calls fs.Open and uses Read and Closeon the returnedFile.

Example
package mainimport ("fmt""io/fs""log""testing/fstest")func main() {fsys := fstest.MapFS{"hello.txt": {Data: []byte("Hello, World!\n"),},}data, err := fs.ReadFile(fsys, "hello.txt")if err != nil {log.Fatal(err)}fmt.Print(string(data))}
Output:Hello, World!

funcReadLinkadded ingo1.25.0

func ReadLink(fsysFS, namestring) (string,error)

ReadLink returns the destination of the named symbolic link.

If fsys does not implementReadLinkFS, then ReadLink returns an error.

funcValidPath

func ValidPath(namestring)bool

ValidPath reports whether the given path nameis valid for use in a call to Open.

Path names passed to open are UTF-8-encoded,unrooted, slash-separated sequences of path elements, like “x/y/z”.Path names must not contain an element that is “.” or “..” or the empty string,except for the special case that the name "." may be used for the root directory.Paths must not start or end with a slash: “/x” and “x/” are invalid.

Note that paths are slash-separated on all systems, even Windows.Paths containing other characters such as backslash and colonare accepted as valid, but those characters must never beinterpreted by anFS implementation as path element separators.

Example
package mainimport ("fmt""io/fs")func main() {paths := []string{".","x","x/y/z","","..","/x","x/","x//y","x/./y","x/../y",}for _, path := range paths {fmt.Printf("ValidPath(%q) = %t\n", path, fs.ValidPath(path))}}
Output:ValidPath(".") = trueValidPath("x") = trueValidPath("x/y/z") = trueValidPath("") = falseValidPath("..") = falseValidPath("/x") = falseValidPath("x/") = falseValidPath("x//y") = falseValidPath("x/./y") = falseValidPath("x/../y") = false

funcWalkDir

func WalkDir(fsysFS, rootstring, fnWalkDirFunc)error

WalkDir walks the file tree rooted at root, calling fn for each file ordirectory in the tree, including root.

All errors that arise visiting files and directories are filtered by fn:see thefs.WalkDirFunc documentation for details.

The files are walked in lexical order, which makes the output deterministicbut requires WalkDir to read an entire directory into memory before proceedingto walk that directory.

WalkDir does not follow symbolic links found in directories,but if root itself is a symbolic link, its target will be walked.

Example
package mainimport ("fmt""io/fs""log""os")func main() {root := "/usr/local/go/bin"fileSystem := os.DirFS(root)fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {if err != nil {log.Fatal(err)}fmt.Println(path)return nil})}

Types

typeDirEntry

type DirEntry interface {// Name returns the name of the file (or subdirectory) described by the entry.// This name is only the final element of the path (the base name), not the entire path.// For example, Name would return "hello.go" not "home/gopher/hello.go".Name()string// IsDir reports whether the entry describes a directory.IsDir()bool// Type returns the type bits for the entry.// The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.Type()FileMode// Info returns the FileInfo for the file or subdirectory described by the entry.// The returned FileInfo may be from the time of the original directory read// or from the time of the call to Info. If the file has been removed or renamed// since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).// If the entry denotes a symbolic link, Info reports the information about the link itself,// not the link's target.Info() (FileInfo,error)}

A DirEntry is an entry read from a directory(using theReadDir function or aReadDirFile's ReadDir method).

funcFileInfoToDirEntryadded ingo1.17

func FileInfoToDirEntry(infoFileInfo)DirEntry

FileInfoToDirEntry returns aDirEntry that returns information from info.If info is nil, FileInfoToDirEntry returns nil.

funcReadDir

func ReadDir(fsysFS, namestring) ([]DirEntry,error)

ReadDir reads the named directoryand returns a list of directory entries sorted by filename.

If fs implementsReadDirFS, ReadDir calls fs.ReadDir.Otherwise ReadDir calls fs.Open and uses ReadDir and Closeon the returned file.

typeFS

type FS interface {// Open opens the named file.// [File.Close] must be called to release any associated resources.//// When Open returns an error, it should be of type *PathError// with the Op field set to "open", the Path field set to name,// and the Err field describing the problem.//// Open should reject attempts to open names that do not satisfy// ValidPath(name), returning a *PathError with Err set to// ErrInvalid or ErrNotExist.Open(namestring) (File,error)}

An FS provides access to a hierarchical file system.

The FS interface is the minimum implementation required of the file system.A file system may implement additional interfaces,such asReadFileFS, to provide additional or optimized functionality.

testing/fstest.TestFS may be used to test implementations of an FS forcorrectness.

funcSub

func Sub(fsysFS, dirstring) (FS,error)

Sub returns anFS corresponding to the subtree rooted at fsys's dir.

If dir is ".", Sub returns fsys unchanged.Otherwise, if fs implementsSubFS, Sub returns fsys.Sub(dir).Otherwise, Sub returns a newFS implementation sub that,in effect, implements sub.Open(name) as fsys.Open(path.Join(dir, name)).The implementation also translates calls to ReadDir, ReadFile,ReadLink, Lstat, and Glob appropriately.

Note that Sub(os.DirFS("/"), "prefix") is equivalent to os.DirFS("/prefix")and that neither of them guarantees to avoid operating systemaccesses outside "/prefix", because the implementation ofos.DirFSdoes not check for symbolic links inside "/prefix" that point toother directories. That is,os.DirFS is not a general substitute for achroot-style security mechanism, and Sub does not change that fact.

typeFile

type File interface {Stat() (FileInfo,error)Read([]byte) (int,error)Close()error}

A File provides access to a single file.The File interface is the minimum implementation required of the file.Directory files should also implementReadDirFile.A file may implementio.ReaderAt orio.Seeker as optimizations.

typeFileInfo

type FileInfo interface {Name()string// base name of the fileSize()int64// length in bytes for regular files; system-dependent for othersMode()FileMode// file mode bitsModTime()time.Time// modification timeIsDir()bool// abbreviation for Mode().IsDir()Sys()any// underlying data source (can return nil)}

A FileInfo describes a file and is returned byStat.

funcLstatadded ingo1.25.0

func Lstat(fsysFS, namestring) (FileInfo,error)

Lstat returns aFileInfo describing the named file.If the file is a symbolic link, the returnedFileInfo describes the symbolic link.Lstat makes no attempt to follow the link.

If fsys does not implementReadLinkFS, then Lstat is identical toStat.

funcStat

func Stat(fsysFS, namestring) (FileInfo,error)

Stat returns aFileInfo describing the named file from the file system.

If fs implementsStatFS, Stat calls fs.Stat.Otherwise, Stat opens theFile to stat it.

typeFileMode

type FileModeuint32

A FileMode represents a file's mode and permission bits.The bits have the same definition on all systems, so thatinformation about files can be moved from one systemto another portably. Not all bits apply to all systems.The only required bit isModeDir for directories.

const (// The single letters are the abbreviations// used by the String method's formatting.ModeDirFileMode = 1 << (32 - 1 -iota)// d: is a directoryModeAppend// a: append-onlyModeExclusive// l: exclusive useModeTemporary// T: temporary file; Plan 9 onlyModeSymlink// L: symbolic linkModeDevice// D: device fileModeNamedPipe// p: named pipe (FIFO)ModeSocket// S: Unix domain socketModeSetuid// u: setuidModeSetgid// g: setgidModeCharDevice// c: Unix character device, when ModeDevice is setModeSticky// t: stickyModeIrregular// ?: non-regular file; nothing else is known about this file// Mask for the type bits. For regular files, none will be set.ModeType =ModeDir |ModeSymlink |ModeNamedPipe |ModeSocket |ModeDevice |ModeCharDevice |ModeIrregularModePermFileMode = 0777// Unix permission bits)

The defined file mode bits are the most significant bits of theFileMode.The nine least-significant bits are the standard Unix rwxrwxrwx permissions.The values of these bits should be considered part of the public API andmay be used in wire protocols or disk representations: they must not bechanged, although new bits might be added.

func (FileMode)IsDir

func (mFileMode) IsDir()bool

IsDir reports whether m describes a directory.That is, it tests for theModeDir bit being set in m.

func (FileMode)IsRegular

func (mFileMode) IsRegular()bool

IsRegular reports whether m describes a regular file.That is, it tests that no mode type bits are set.

func (FileMode)Perm

func (mFileMode) Perm()FileMode

Perm returns the Unix permission bits in m (m &ModePerm).

func (FileMode)String

func (mFileMode) String()string

func (FileMode)Type

func (mFileMode) Type()FileMode

Type returns type bits in m (m &ModeType).

typeGlobFS

type GlobFS interface {FS// Glob returns the names of all files matching pattern,// providing an implementation of the top-level// Glob function.Glob(patternstring) ([]string,error)}

A GlobFS is a file system with a Glob method.

typePathError

type PathError struct {OpstringPathstringErrerror}

PathError records an error and the operation and file path that caused it.

func (*PathError)Error

func (e *PathError) Error()string

func (*PathError)Timeout

func (e *PathError) Timeout()bool

Timeout reports whether this error represents a timeout.

func (*PathError)Unwrap

func (e *PathError) Unwrap()error

typeReadDirFS

type ReadDirFS interface {FS// ReadDir reads the named directory// and returns a list of directory entries sorted by filename.ReadDir(namestring) ([]DirEntry,error)}

ReadDirFS is the interface implemented by a file systemthat provides an optimized implementation ofReadDir.

typeReadDirFile

type ReadDirFile interface {File// ReadDir reads the contents of the directory and returns// a slice of up to n DirEntry values in directory order.// Subsequent calls on the same file will yield further DirEntry values.//// If n > 0, ReadDir returns at most n DirEntry structures.// In this case, if ReadDir returns an empty slice, it will return// a non-nil error explaining why.// At the end of a directory, the error is io.EOF.// (ReadDir must return io.EOF itself, not an error wrapping io.EOF.)//// If n <= 0, ReadDir returns all remaining DirEntry values from the directory// in a single slice. In this case, if ReadDir succeeds (reads all the way// to the end of the directory), it returns the slice and a nil error.// If it encounters an error before the end of the directory,// ReadDir returns the DirEntry list read until that point and a non-nil error.ReadDir(nint) ([]DirEntry,error)}

A ReadDirFile is a directory file whose entries can be read with the ReadDir method.Every directory file should implement this interface.(It is permissible for any file to implement this interface,but if so ReadDir should return an error for non-directories.)

typeReadFileFS

type ReadFileFS interface {FS// ReadFile reads the named file and returns its contents.// A successful call returns a nil error, not io.EOF.// (Because ReadFile reads the whole file, the expected EOF// from the final Read is not treated as an error to be reported.)//// The caller is permitted to modify the returned byte slice.// This method should return a copy of the underlying data.ReadFile(namestring) ([]byte,error)}

ReadFileFS is the interface implemented by a file systemthat provides an optimized implementation ofReadFile.

typeReadLinkFSadded ingo1.25.0

type ReadLinkFS interface {FS// ReadLink returns the destination of the named symbolic link.// If there is an error, it should be of type [*PathError].ReadLink(namestring) (string,error)// Lstat returns a [FileInfo] describing the named file.// If the file is a symbolic link, the returned [FileInfo] describes the symbolic link.// Lstat makes no attempt to follow the link.// If there is an error, it should be of type [*PathError].Lstat(namestring) (FileInfo,error)}

ReadLinkFS is the interface implemented by a file systemthat supports reading symbolic links.

typeStatFS

type StatFS interface {FS// Stat returns a FileInfo describing the file.// If there is an error, it should be of type *PathError.Stat(namestring) (FileInfo,error)}

A StatFS is a file system with a Stat method.

typeSubFS

type SubFS interface {FS// Sub returns an FS corresponding to the subtree rooted at dir.Sub(dirstring) (FS,error)}

A SubFS is a file system with a Sub method.

typeWalkDirFunc

type WalkDirFunc func(pathstring, dDirEntry, errerror)error

WalkDirFunc is the type of the function called byWalkDir to visiteach file or directory.

The path argument contains the argument toWalkDir as a prefix.That is, if WalkDir is called with root argument "dir" and finds a filenamed "a" in that directory, the walk function will be called withargument "dir/a".

The d argument is theDirEntry for the named path.

The error result returned by the function controls howWalkDircontinues. If the function returns the special valueSkipDir, WalkDirskips the current directory (path if d.IsDir() is true, otherwisepath's parent directory). If the function returns the special valueSkipAll, WalkDir skips all remaining files and directories. Otherwise,if the function returns a non-nil error, WalkDir stops entirely andreturns that error.

The err argument reports an error related to path, signaling thatWalkDir will not walk into that directory. The function can decide howto handle that error; as described earlier, returning the error willcause WalkDir to stop walking the entire tree.

WalkDir calls the function with a non-nil err argument in two cases.

First, if the initialStat on the root directory fails, WalkDircalls the function with path set to root, d set to nil, and err set tothe error fromfs.Stat.

Second, if a directory's ReadDir method (seeReadDirFile) fails, WalkDir calls thefunction with path set to the directory's path, d set to anDirEntry describing the directory, and err set to the error fromReadDir. In this second case, the function is called twice with thepath of the directory: the first call is before the directory read isattempted and has err set to nil, giving the function a chance toreturnSkipDir orSkipAll and avoid the ReadDir entirely. The second callis after a failed ReadDir and reports the error from ReadDir.(If ReadDir succeeds, there is no second call.)

The differences between WalkDirFunc compared topath/filepath.WalkFunc are:

  • The second argument has typeDirEntry instead ofFileInfo.
  • The function is called before reading a directory, to allowSkipDirorSkipAll to bypass the directory read entirely or skip all remainingfiles and directories respectively.
  • If a directory read fails, the function is called a second timefor that directory to report the error.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp