Documentation ¶
Overview ¶
Package gfile provides easy-to-use operations for file system.
Index ¶
- Constants
- Variables
- func Abs(path string) string
- func Basename(path string) string
- func Chdir(dir string) (err error)
- func Chmod(path string, mode os.FileMode) (err error)
- func Copy(src string, dst string, option ...CopyOption) error
- func CopyDir(src string, dst string, option ...CopyOption) (err error)
- func CopyFile(src, dst string, option ...CopyOption) (err error)
- func Create(path string) (*os.File, error)
- func Dir(path string) string
- func DirNames(path string) ([]string, error)
- func Exists(path string) bool
- func Ext(path string) string
- func ExtName(path string) string
- func FormatSize(raw int64) string
- func GetBytes(path string) []byte
- func GetBytesByTwoOffsets(reader io.ReaderAt, start int64, end int64) []byte
- func GetBytesByTwoOffsetsByPath(path string, start int64, end int64) []byte
- func GetBytesTilChar(reader io.ReaderAt, char byte, start int64) ([]byte, int64)
- func GetBytesTilCharByPath(path string, char byte, start int64) ([]byte, int64)
- func GetContents(path string) string
- func GetNextCharOffset(reader io.ReaderAt, char byte, start int64) int64
- func GetNextCharOffsetByPath(path string, char byte, start int64) int64
- func Glob(pattern string, onlyNames ...bool) ([]string, error)
- func Home(names ...string) (string, error)
- func IsDir(path string) bool
- func IsEmpty(path string) bool
- func IsFile(path string) bool
- func IsReadable(path string) bool
- func IsWritable(path string) bool
- func Join(paths ...string) string
- func MTime(path string) time.Time
- func MTimestamp(path string) int64
- func MTimestampMilli(path string) int64
- func MainPkgPath() string
- func Mkdir(path string) (err error)
- func Move(src string, dst string) (err error)
- func Name(path string) string
- func Open(path string) (*os.File, error)
- func OpenFile(path string, flag int, perm os.FileMode) (*os.File, error)
- func OpenWithFlag(path string, flag int) (*os.File, error)
- func OpenWithFlagPerm(path string, flag int, perm os.FileMode) (*os.File, error)
- func PutBytes(path string, content []byte) error
- func PutBytesAppend(path string, content []byte) error
- func PutContents(path string, content string) error
- func PutContentsAppend(path string, content string) error
- func Pwd() string
- func ReadLines(file string, callback func(line string) error) error
- func ReadLinesBytes(file string, callback func(bytes []byte) error) error
- func ReadableSize(path string) string
- func RealPath(path string) string
- func Remove(path string) (err error)
- func Rename(src string, dst string) error
- func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error
- func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error
- func ReplaceFile(search, replace, path string) error
- func ReplaceFileFunc(f func(path, content string) string, path string) error
- func ScanDir(path string, pattern string, recursive ...bool) ([]string, error)
- func ScanDirFile(path string, pattern string, recursive ...bool) ([]string, error)
- func ScanDirFileFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
- func ScanDirFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
- func Search(name string, prioritySearchPaths ...string) (realPath string, err error)
- func SelfDir() string
- func SelfName() string
- func SelfPath() string
- func Size(path string) int64
- func SizeFormat(path string) string
- func SortFiles(files []string) []string
- func Stat(path string) (os.FileInfo, error)
- func StrToSize(sizeStr string) int64
- func Temp(names ...string) string
- func Truncate(path string, size int) (err error)
- type CopyOption
Examples ¶
- Abs
- Basename
- Chdir
- Chmod
- Copy
- Create
- Dir
- DirNames
- Exists
- Ext
- ExtName
- FormatSize
- GetBytes
- GetBytesByTwoOffsetsByPath
- GetBytesTilCharByPath
- GetContents
- GetNextCharOffsetByPath
- Glob
- Home
- IsDir
- IsEmpty
- IsFile
- IsReadable
- IsWritable
- Join
- MTime
- MTimestamp
- MTimestampMilli
- Mkdir
- Move
- Name
- Open
- OpenFile
- OpenWithFlag
- PutBytes
- PutBytesAppend
- PutContents
- PutContentsAppend
- Pwd
- ReadLines
- ReadLinesBytes
- ReadableSize
- RealPath
- Remove
- Rename
- ReplaceDir
- ReplaceDirFunc
- ReplaceFile
- ReplaceFileFunc
- ScanDir
- ScanDirFile
- ScanDirFileFunc
- ScanDirFunc
- Search
- SelfDir
- SelfName
- SelfPath
- Size
- SizeFormat
- SortFiles
- Stat
- StrToSize
Constants ¶
const ( // Separator for file system. // It here defines the separator as variable // to allow it modified by developer if necessary. Separator = string(filepath.Separator) // DefaultPermOpen is the default perm for file opening. DefaultPermOpen = os.FileMode(0666) // DefaultPermCopy is the default perm for file/folder copy. DefaultPermCopy = os.FileMode(0755) )
Variables ¶
var (
// DefaultReadBuffer is the buffer size for reading file content.
DefaultReadBuffer = 1024
)
Functions ¶
func Abs ¶
Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get an absolute representation of path. fmt.Println(gfile.Abs(path)) // May Output: // /tmp/gfile_example_basic_dir/file1 }
Output:
func Basename ¶
Basename returns the last element of path, which contains file extension. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Basename returns a single separator.
Example: Basename("/var/www/file.js") -> file.js Basename("file.js") -> file.js
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log" ) // Get the last element of path, which contains file extension. fmt.Println(gfile.Basename(path)) }
Output: file.log
func Chdir ¶
Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get current working directory fmt.Println(gfile.Pwd()) // Changes the current working directory to the named directory. gfile.Chdir(path) // Get current working directory fmt.Println(gfile.Pwd()) // May Output: // xxx/gf/os/gfile // /tmp/gfile_example_basic_dir/file1 }
Output:
func Chmod ¶
Chmod is alias of os.Chmod. See os.Chmod.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get a FileInfo describing the named file. stat, err := gfile.Stat(path) if err != nil { fmt.Println(err.Error()) } // Show original mode fmt.Println(stat.Mode()) // Change file model gfile.Chmod(path, gfile.DefaultPermCopy) // Get a FileInfo describing the named file. stat, _ = gfile.Stat(path) // Show the modified mode fmt.Println(stat.Mode()) }
Output: -rw-r--r-- -rwxr-xr-x
func Copy ¶
func Copy(src string, dst string, option ...CopyOption) error
Copy file/directory from `src` to `dst`.
If `src` is file, it calls CopyFile to implements copy feature, or else it calls CopyDir.
If `src` is file, but `dst` already exists and is a folder, it then creates a same name file of `src` in folder `dst`.
Eg: Copy("/tmp/file1", "/tmp/file2") => /tmp/file1 copied to /tmp/file2 Copy("/tmp/dir1", "/tmp/dir2") => /tmp/dir1 copied to /tmp/dir2 Copy("/tmp/file1", "/tmp/dir2") => /tmp/file1 copied to /tmp/dir2/file1 Copy("/tmp/dir1", "/tmp/file2") => error
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( srcFileName = "gfile_example.txt" srcTempDir = gfile.Temp("gfile_example_copy_src") srcTempFile = gfile.Join(srcTempDir, srcFileName) // copy file dstFileName = "gfile_example_copy.txt" dstTempFile = gfile.Join(srcTempDir, dstFileName) // copy dir dstTempDir = gfile.Temp("gfile_example_copy_dst") ) // write contents gfile.PutContents(srcTempFile, "goframe example copy") // copy file gfile.Copy(srcTempFile, dstTempFile) // read contents after copy file fmt.Println(gfile.GetContents(dstTempFile)) // copy dir gfile.Copy(srcTempDir, dstTempDir) // list copy dir file fList, _ := gfile.ScanDir(dstTempDir, "*", false) for _, v := range fList { fmt.Println(gfile.Basename(v)) } }
Output: goframe example copy gfile_example.txt gfile_example_copy.txt
func CopyDir ¶
func CopyDir(src string, dst string, option ...CopyOption) (err error)
CopyDir recursively copies a directory tree, attempting to preserve permissions.
Note that, the Source directory must exist and symlinks are ignored and skipped.
func CopyFile ¶
func CopyFile(src, dst string, option ...CopyOption) (err error)
CopyFile copies the contents of the file named `src` to the file named by `dst`. The file will be created if it does not exist. If the destination file exists, all it's contents will be replaced by the contents of the source file. The file mode will be copied from the source and the copied data is synced/flushed to stable storage. Thanks: https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04
func Create ¶
Create creates a file with given `path` recursively. The parameter `path` is suggested to be absolute path.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 50) ) // Check whether the file exists isFile := gfile.IsFile(path) fmt.Println(isFile) // Creates file with given `path` recursively fileHandle, _ := gfile.Create(path) defer fileHandle.Close() // Write some content to file n, _ := fileHandle.WriteString("hello goframe") // Check whether the file exists isFile = gfile.IsFile(path) fmt.Println(isFile) // Reads len(b) bytes from the File fileHandle.ReadAt(dataByte, 0) fmt.Println(string(dataByte[:n])) }
Output: false true hello goframe
func Dir ¶
Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the `path` is empty, Dir returns ".". If the `path` is ".", Dir treats the path as current working directory. If the `path` consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.
Example: Dir("/var/www/file.js") -> "/var/www" Dir("file.js") -> "."
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get all but the last element of path, typically the path's directory. fmt.Println(gfile.Dir(path)) // May Output: // /tmp/gfile_example_basic_dir }
Output:
func DirNames ¶
DirNames returns sub-file names of given directory `path`. Note that the returned names are NOT absolute paths.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Temp("gfile_example_basic_dir") ) // Get sub-file names of given directory `path`. dirNames, _ := gfile.DirNames(path) fmt.Println(dirNames) // May Output: // [file1] }
Output:
func Exists ¶
Exists checks whether given `path` exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` exist. joinString := gfile.Exists(path) fmt.Println(joinString) }
Output: true
func Ext ¶
Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot. Note: the result contains symbol '.'.
Example: Ext("main.go") => .go Ext("api.json") => .json
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log" ) // Get the file name extension used by path. fmt.Println(gfile.Ext(path)) }
Output: .log
func ExtName ¶
ExtName is like function Ext, which returns the file name extension used by path, but the result does not contain symbol '.'.
Example: ExtName("main.go") => go ExtName("api.json") => json
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log" ) // Get the file name extension used by path but the result does not contains symbol '.'. fmt.Println(gfile.ExtName(path)) }
Output: log
func FormatSize ¶
FormatSize formats size `raw` for more manually readable.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { sizeStr := gfile.FormatSize(104857600) fmt.Println(sizeStr) sizeStr0 := gfile.FormatSize(1024) fmt.Println(sizeStr0) sizeStr1 := gfile.FormatSize(999999999999999999) fmt.Println(sizeStr1) }
Output: 100.00M 1.00K 888.18P
func GetBytes ¶
GetBytes returns the file content of `path` as []byte. It returns nil if it fails reading.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // It reads and returns the file content as []byte. // It returns nil if it fails reading, for example, with permission or IO error. fmt.Println(gfile.GetBytes(tempFile)) }
Output: [103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
func GetBytesByTwoOffsets ¶
GetBytesByTwoOffsets returns the binary content as []byte from `start` to `end`. Note: Returned value does not contain the character of the last position, which means it returns content range as [start, end).
func GetBytesByTwoOffsetsByPath ¶
GetBytesByTwoOffsetsByPath returns the binary content as []byte from `start` to `end`. Note: Returned value does not contain the character of the last position, which means it returns content range as [start, end). It opens file of `path` for reading with os.O_RDONLY flag and default perm.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetBytesByTwoOffsetsByPath(tempFile, 0, 7)) }
Output: [103 111 102 114 97 109 101]
func GetBytesTilChar ¶
GetBytesTilChar returns the contents of the file as []byte until the next specified byte `char` position.
Note: Returned value contains the character of the last position.
func GetBytesTilCharByPath ¶
GetBytesTilCharByPath returns the contents of the file given by `path` as []byte until the next specified byte `char` position. It opens file of `path` for reading with os.O_RDONLY flag and default perm.
Note: Returned value contains the character of the last position.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetBytesTilCharByPath(tempFile, 'f', 0)) }
Output: [103 111 102] 2
func GetContents ¶
GetContents returns the file content of `path` as string. It returns en empty string if it fails reading.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // It reads and returns the file content as string. // It returns empty string if it fails reading, for example, with permission or IO error. fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content
func GetNextCharOffset ¶
GetNextCharOffset returns the file offset for given `char` starting from `start`.
func GetNextCharOffsetByPath ¶
GetNextCharOffsetByPath returns the file offset for given `char` starting from `start`. It opens file of `path` for reading with os.O_RDONLY flag and default perm.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents index := gfile.GetNextCharOffsetByPath(tempFile, 'f', 0) fmt.Println(index) }
Output: 2
func Glob ¶
Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the Separator is '/').
Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "*_example_basic_test.go" ) // Get sub-file names of given directory `path`. // Only show file name matchNames, _ := gfile.Glob(path, true) fmt.Println(matchNames) // Show full path of the file matchNames, _ = gfile.Glob(path, false) fmt.Println(matchNames) // May Output: // [gfile_z_example_basic_test.go] // [xxx/gf/os/gfile/gfile_z_example_basic_test.go] }
Output:
func Home ¶
Home returns absolute path of current user's home directory. The optional parameter `names` specifies the sub-folders/sub-files, which will be joined with current system separator and returned with the path.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // user's home directory homePath, _ := gfile.Home() fmt.Println(homePath) // May Output: // C:\Users\hailaz }
Output:
func IsDir ¶
IsDir checks whether given `path` a directory. Note that it returns false if the `path` does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Temp("gfile_example_basic_dir") filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` a directory. fmt.Println(gfile.IsDir(path)) fmt.Println(gfile.IsDir(filePath)) }
Output: true false
func IsEmpty ¶
IsEmpty checks whether the given `path` is empty. If `path` is a folder, it checks if there's any file under it. If `path` is a file, it checks if the file size is zero.
Note that it returns true if `path` does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Check whether the `path` is empty fmt.Println(gfile.IsEmpty(path)) // Truncate file gfile.Truncate(path, 0) // Check whether the `path` is empty fmt.Println(gfile.IsEmpty(path)) }
Output: false true
func IsFile ¶
IsFile checks whether given `path` a file, which means it's not a directory. Note that it returns false if the `path` does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( filePath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dirPath = gfile.Temp("gfile_example_basic_dir") ) // Checks whether given `path` a file, which means it's not a directory. fmt.Println(gfile.IsFile(filePath)) fmt.Println(gfile.IsFile(dirPath)) }
Output: true false
func IsReadable ¶
IsReadable checks whether given `path` is readable.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log" ) // Checks whether given `path` is readable. fmt.Println(gfile.IsReadable(path)) }
Output: true
func IsWritable ¶
IsWritable checks whether given `path` is writable.
TODO improve performance; use golang.org/x/sys to cross-plat-form
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/" file = "file.log" ) // Checks whether given `path` is writable. fmt.Println(gfile.IsWritable(path)) fmt.Println(gfile.IsWritable(path + file)) }
Output: true true
func Join ¶
Join joins string array paths with file separator of current system.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( dirPath = gfile.Temp("gfile_example_basic_dir") filePath = "file1" ) // Joins string array paths with file separator of current system. joinString := gfile.Join(dirPath, filePath) fmt.Println(joinString) // May Output: // /tmp/gfile_example_basic_dir/file1 }
Output:
func MTime ¶
MTime returns the modification time of file given by `path` in second.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { t := gfile.MTime(gfile.Temp()) fmt.Println(t) // May Output: // 2021-11-02 15:18:43.901141 +0800 CST }
Output:
func MTimestamp ¶
MTimestamp returns the modification time of file given by `path` in second.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { t := gfile.MTimestamp(gfile.Temp()) fmt.Println(t) // May Output: // 1635838398 }
Output:
func MTimestampMilli ¶
MTimestampMilli returns the modification time of file given by `path` in millisecond.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { t := gfile.MTimestampMilli(gfile.Temp()) fmt.Println(t) // May Output: // 1635838529330 }
Output:
func MainPkgPath ¶
func MainPkgPath() string
MainPkgPath returns absolute file path of package main, which contains the entrance function main.
It's only available in develop environment.
Note1: Only valid for source development environments, IE only valid for systems that generate this executable.
Note2: When the method is called for the first time, if it is in an asynchronous goroutine, the method may not get the main package path.
func Mkdir ¶
Mkdir creates directories recursively with given `path`. The parameter `path` is suggested to be an absolute path instead of relative one.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Temp("gfile_example_basic_dir") ) // Creates directory gfile.Mkdir(path) // Check if directory exists fmt.Println(gfile.IsDir(path)) }
Output: true
func Move ¶
Move renames (moves) `src` to `dst` path. If `dst` already exists and is not a directory, it'll be replaced.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2") ) // Check is file fmt.Println(gfile.IsFile(dstPath)) // Moves `src` to `dst` path. // If `dst` already exists and is not a directory, it'll be replaced. gfile.Move(srcPath, dstPath) fmt.Println(gfile.IsFile(srcPath)) fmt.Println(gfile.IsFile(dstPath)) }
Output: false false true
func Name ¶
Name returns the last element of path without file extension.
Example: Name("/var/www/file.js") -> file Name("file.js") -> file
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Pwd() + gfile.Separator + "testdata/readline/file.log" ) // Get the last element of path without file extension. fmt.Println(gfile.Name(path)) }
Output: file
func Open ¶
Open opens file/directory READONLY.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) // Open file or directory with READONLY model file, _ := gfile.Open(path) defer file.Close() // Read data n, _ := file.Read(dataByte) fmt.Println(string(dataByte[:n])) }
Output: hello goframe
func OpenFile ¶
OpenFile opens file/directory with custom `flag` and `perm`. The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc.
Example ¶
package main import ( "fmt" "os" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) // Opens file/directory with custom `flag` and `perm` // Create if file does not exist,it is created in a readable and writable mode,prem 0777 openFile, _ := gfile.OpenFile(path, os.O_CREATE|os.O_RDWR, gfile.DefaultPermCopy) defer openFile.Close() // Write some content to file writeLength, _ := openFile.WriteString("hello goframe test open file") fmt.Println(writeLength) // Read data n, _ := openFile.ReadAt(dataByte, 0) fmt.Println(string(dataByte[:n])) }
Output: 28 hello goframe test open file
func OpenWithFlag ¶
OpenWithFlag opens file/directory with default perm and custom `flag`. The default `perm` is 0666. The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc.
Example ¶
package main import ( "fmt" "os" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") dataByte = make([]byte, 4096) ) // Opens file/directory with custom `flag` // Create if file does not exist,it is created in a readable and writable mode with default `perm` is 0666 openFile, _ := gfile.OpenWithFlag(path, os.O_CREATE|os.O_RDWR) defer openFile.Close() // Write some content to file writeLength, _ := openFile.WriteString("hello goframe test open file with flag") fmt.Println(writeLength) // Read data n, _ := openFile.ReadAt(dataByte, 0) fmt.Println(string(dataByte[:n])) }
Output: 38 hello goframe test open file with flag
func OpenWithFlagPerm ¶
OpenWithFlagPerm opens file/directory with custom `flag` and `perm`. The parameter `flag` is like: O_RDONLY, O_RDWR, O_RDWR|O_CREATE|O_TRUNC, etc. The parameter `perm` is like: 0600, 0666, 0777, etc.
func PutBytes ¶
PutBytes puts binary `content` to file of `path`. It creates file of `path` recursively if it does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutBytes(tempFile, []byte("goframe example content")) // read contents fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content
func PutBytesAppend ¶
PutBytesAppend appends binary `content` to file of `path`. It creates file of `path` recursively if it does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetContents(tempFile)) // write contents gfile.PutBytesAppend(tempFile, []byte(" append")) // read contents fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content goframe example content append
func PutContents ¶
PutContents puts string `content` to file of `path`. It creates file of `path` recursively if it does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // It creates and puts content string into specifies file path. // It automatically creates directory recursively if it does not exist. gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content
func PutContentsAppend ¶
PutContentsAppend appends string `content` to file of `path`. It creates file of `path` recursively if it does not exist.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetContents(tempFile)) // It creates and append content string into specifies file path. // It automatically creates directory recursively if it does not exist. gfile.PutContentsAppend(tempFile, " append content") // read contents fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content goframe example content append content
func Pwd ¶
func Pwd() string
Pwd returns absolute path of current working directory. Note that it returns an empty string if retrieving current working directory failed.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // Get absolute path of current working directory. fmt.Println(gfile.Pwd()) // May Output: // xxx/gf/os/gfile }
Output:
func ReadLines ¶
ReadLines reads file content line by line, which is passed to the callback function `callback` as string. It matches each line of text, separated by chars '\r' or '\n', stripped any trailing end-of-line marker.
Note that the parameter passed to callback function might be an empty value, and the last non-empty line will be passed to callback function `callback` even if it has no newline marker.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content") // read contents gfile.ReadLines(tempFile, func(text string) error { // Process each line fmt.Println(text) return nil }) }
Output: L1 goframe example content L2 goframe example content
func ReadLinesBytes ¶
ReadLinesBytes reads file content line by line, which is passed to the callback function `callback` as []byte. It matches each line of text, separated by chars '\r' or '\n', stripped any trailing end-of-line marker.
Note that the parameter passed to callback function might be an empty value, and the last non-empty line will be passed to callback function `callback` even if it has no newline marker.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_content") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "L1 goframe example content\nL2 goframe example content") // read contents gfile.ReadLinesBytes(tempFile, func(bytes []byte) error { // Process each line fmt.Println(bytes) return nil }) }
Output: [76 49 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116] [76 50 32 103 111 102 114 97 109 101 32 101 120 97 109 112 108 101 32 99 111 110 116 101 110 116]
func ReadableSize ¶
ReadableSize formats size of file given by `path`, for more human readable.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "01234567899876543210") fmt.Println(gfile.ReadableSize(tempFile)) }
Output: 20.00B
func RealPath ¶
RealPath converts the given `path` to its absolute path and checks if the file path exists. If the file does not exist, return an empty string.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( realPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") worryPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "worryFile") ) // fetch an absolute representation of path. fmt.Println(gfile.RealPath(realPath)) fmt.Println(gfile.RealPath(worryPath)) // May Output: // /tmp/gfile_example_basic_dir/file1 }
Output:
func Remove ¶
Remove deletes all file/directory with `path` parameter. If parameter `path` is directory, it deletes it recursively.
It does nothing if given `path` does not exist or is empty.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Checks whether given `path` a file, which means it's not a directory. fmt.Println(gfile.IsFile(path)) // deletes all file/directory with `path` parameter. gfile.Remove(path) // Check again fmt.Println(gfile.IsFile(path)) }
Output: true false
func Rename ¶
Rename is alias of Move. See Move.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( srcPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file2") dstPath = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Check is file fmt.Println(gfile.IsFile(dstPath)) // renames (moves) `src` to `dst` path. // If `dst` already exists and is not a directory, it'll be replaced. gfile.Rename(srcPath, dstPath) fmt.Println(gfile.IsFile(srcPath)) fmt.Println(gfile.IsFile(dstPath)) }
Output: false false true
func ReplaceDir ¶
ReplaceDir replaces content for files under `path`. The parameter `pattern` specifies the file pattern which matches to be replaced. It does replacement recursively if given parameter `recursive` is true.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetContents(tempFile)) // It replaces content of all files under specified directory recursively. gfile.ReplaceDir("content", "replace word", tempDir, "gfile_example.txt", true) // read contents fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content goframe example replace word
func ReplaceDirFunc ¶
func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error
ReplaceDirFunc replaces content for files under `path` with callback function `f`. The parameter `pattern` specifies the file pattern which matches to be replaced. It does replacement recursively if given parameter `recursive` is true.
Example ¶
package main import ( "fmt" "regexp" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example 123") // read contents fmt.Println(gfile.GetContents(tempFile)) // It replaces content of all files under specified directory with custom callback function recursively. gfile.ReplaceDirFunc(func(path, content string) string { // Replace with regular match reg, _ := regexp.Compile(`\d{3}`) return reg.ReplaceAllString(content, "[num]") }, tempDir, "gfile_example.txt", true) fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example 123 goframe example [num]
func ReplaceFile ¶
ReplaceFile replaces content for file `path`.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // read contents fmt.Println(gfile.GetContents(tempFile)) // It replaces content directly by file path. gfile.ReplaceFile("content", "replace word", tempFile) fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example content goframe example replace word
func ReplaceFileFunc ¶
ReplaceFileFunc replaces content for file `path` with callback function `f`.
Example ¶
package main import ( "fmt" "regexp" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_replace") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example 123") // read contents fmt.Println(gfile.GetContents(tempFile)) // It replaces content directly by file path and callback function. gfile.ReplaceFileFunc(func(path, content string) string { // Replace with regular match reg, _ := regexp.Compile(`\d{3}`) return reg.ReplaceAllString(content, "[num]") }, tempFile) fmt.Println(gfile.GetContents(tempFile)) }
Output: goframe example 123 goframe example [num]
func ScanDir ¶
ScanDir returns all sub-files with absolute paths of given `path`, It scans directory recursively if given parameter `recursive` is true.
The pattern parameter `pattern` supports multiple file name patterns, using the ',' symbol to separate multiple patterns.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") tempSubFile = gfile.Join(tempSubDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") gfile.PutContents(tempSubFile, "goframe example content") // scans directory recursively list, _ := gfile.ScanDir(tempDir, "*", true) for _, v := range list { fmt.Println(gfile.Basename(v)) } }
Output: gfile_example.txt sub_dir gfile_example.txt
func ScanDirFile ¶
ScanDirFile returns all sub-files with absolute paths of given `path`, It scans directory recursively if given parameter `recursive` is true.
The pattern parameter `pattern` supports multiple file name patterns, using the ',' symbol to separate multiple patterns.
Note that it returns only files, exclusive of directories.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_file") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") tempSubFile = gfile.Join(tempSubDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") gfile.PutContents(tempSubFile, "goframe example content") // scans directory recursively exclusive of directories list, _ := gfile.ScanDirFile(tempDir, "*.txt", true) for _, v := range list { fmt.Println(gfile.Basename(v)) } }
Output: gfile_example.txt gfile_example.txt
func ScanDirFileFunc ¶
func ScanDirFileFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
ScanDirFileFunc returns all sub-files with absolute paths of given `path`, It scans directory recursively if given parameter `recursive` is true.
The pattern parameter `pattern` supports multiple file name patterns, using the ',' symbol to separate multiple patterns.
The parameter `recursive` specifies whether scanning the `path` recursively, which means it scans its sub-files and appends the file paths to result array if the sub-file is also a folder. It is false in default.
The parameter `handler` specifies the callback function handling each sub-file path of the `path` and its sub-folders. It ignores the sub-file path if `handler` returns an empty string, or else it appends the sub-file path to result slice.
Note that the parameter `path` for `handler` is not a directory but a file. It returns only files, exclusive of directories.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_file_func") tempFile = gfile.Join(tempDir, fileName) fileName1 = "gfile_example_ignores.txt" tempFile1 = gfile.Join(tempDir, fileName1) tempSubDir = gfile.Join(tempDir, "sub_dir") tempSubFile = gfile.Join(tempSubDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") gfile.PutContents(tempFile1, "goframe example content") gfile.PutContents(tempSubFile, "goframe example content") // scans directory recursively exclusive of directories list, _ := gfile.ScanDirFileFunc(tempDir, "*.txt", true, func(path string) string { // ignores some files if gfile.Basename(path) == "gfile_example_ignores.txt" { return "" } return path }) for _, v := range list { fmt.Println(gfile.Basename(v)) } }
Output: gfile_example.txt gfile_example.txt
func ScanDirFunc ¶
func ScanDirFunc(path string, pattern string, recursive bool, handler func(path string) string) ([]string, error)
ScanDirFunc returns all sub-files with absolute paths of given `path`, It scans directory recursively if given parameter `recursive` is true.
The pattern parameter `pattern` supports multiple file name patterns, using the ',' symbol to separate multiple patterns.
The parameter `recursive` specifies whether scanning the `path` recursively, which means it scans its sub-files and appends the files path to result array if the sub-file is also a folder. It is false in default.
The parameter `handler` specifies the callback function handling each sub-file path of the `path` and its sub-folders. It ignores the sub-file path if `handler` returns an empty string, or else it appends the sub-file path to result slice.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_scan_dir_func") tempFile = gfile.Join(tempDir, fileName) tempSubDir = gfile.Join(tempDir, "sub_dir") tempSubFile = gfile.Join(tempSubDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") gfile.PutContents(tempSubFile, "goframe example content") // scans directory recursively list, _ := gfile.ScanDirFunc(tempDir, "*", true, func(path string) string { // ignores some files if gfile.Basename(path) == "gfile_example.txt" { return "" } return path }) for _, v := range list { fmt.Println(gfile.Basename(v)) } }
Output: sub_dir
func Search ¶
Search searches file by name `name` in following paths with priority: prioritySearchPaths, Pwd()、SelfDir()、MainPkgPath(). It returns the absolute file path of `name` if found, or en empty string if not found.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_search") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "goframe example content") // search file realPath, _ := gfile.Search(fileName, tempDir) fmt.Println(gfile.Basename(realPath)) }
Output: gfile_example.txt
func SelfDir ¶
func SelfDir() string
SelfDir returns absolute directory path of current running process(binary).
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // Get absolute directory path of current running process fmt.Println(gfile.SelfDir()) // May Output: // /private/var/folders/p6/gc_9mm3j229c0mjrjp01gqn80000gn/T }
Output:
func SelfName ¶
func SelfName() string
SelfName returns file name of current running process(binary).
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // Get file name of current running process fmt.Println(gfile.SelfName()) // May Output: // ___github_com_gogf_gf_v2_os_gfile__ExampleSelfName }
Output:
func SelfPath ¶
func SelfPath() string
SelfPath returns absolute file path of current running process(binary).
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // Get absolute file path of current running process fmt.Println(gfile.SelfPath()) // May Output: // xxx/___github_com_gogf_gf_v2_os_gfile__ExampleSelfPath }
Output:
func Size ¶
Size returns the size of file specified by `path` in byte.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "0123456789") fmt.Println(gfile.Size(tempFile)) }
Output: 10
func SizeFormat ¶
SizeFormat returns the size of file specified by `path` in format string.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( fileName = "gfile_example.txt" tempDir = gfile.Temp("gfile_example_size") tempFile = gfile.Join(tempDir, fileName) ) // write contents gfile.PutContents(tempFile, "0123456789") fmt.Println(gfile.SizeFormat(tempFile)) }
Output: 10.00B
func SortFiles ¶
SortFiles sorts the `files` in order of: directory -> file. Note that the item of `files` should be absolute path.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { files := []string{ "/aaa/bbb/ccc.txt", "/aaa/bbb/", "/aaa/", "/aaa", "/aaa/ccc/ddd.txt", "/bbb", "/0123", "/ddd", "/ccc", } sortOut := gfile.SortFiles(files) fmt.Println(sortOut) }
Output: [/0123 /aaa /aaa/ /aaa/bbb/ /aaa/bbb/ccc.txt /aaa/ccc/ddd.txt /bbb /ccc /ddd]
func Stat ¶
Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { // init var ( path = gfile.Join(gfile.Temp("gfile_example_basic_dir"), "file1") ) // Get a FileInfo describing the named file. stat, _ := gfile.Stat(path) fmt.Println(stat.Name()) fmt.Println(stat.IsDir()) fmt.Println(stat.Mode()) fmt.Println(stat.ModTime()) fmt.Println(stat.Size()) fmt.Println(stat.Sys()) // May Output: // file1 // false // -rwxr-xr-x // 2021-12-02 11:01:27.261441694 +0800 CST // &{16777220 33261 1 8597857090 501 20 0 [0 0 0 0] {1638414088 192363490} {1638414087 261441694} {1638414087 261441694} {1638413480 485068275} 38 8 4096 0 0 0 [0 0]} }
Output:
func StrToSize ¶
StrToSize converts formatted size string to its size in bytes.
Example ¶
package main import ( "fmt" "gitee.com/iceinto/gfutil/v2/os/gfile" ) func main() { size := gfile.StrToSize("100MB") fmt.Println(size) }
Output: 104857600
Types ¶
type CopyOption ¶
type CopyOption struct { // Auto call file sync after source file content copied to target file. Sync bool // Preserve the mode of the original file to the target file. // If true, the Mode attribute will make no sense. PreserveMode bool // Destination created file mode. // The default file mode is DefaultPermCopy if PreserveMode is false. Mode os.FileMode }
CopyOption is the option for Copy* functions.