Golang 的 os 库基本承袭 Unix 下 C 语言的用法
path 库:
func Base(path string) string //取文件名,不含目录部分
func Dir(path string) string //取路径中的目录名部分,不含文件名
func Join(elem ...string) string //拼接字段,中间自动添加 ‘/’
os 库:
package main import "os"
import "os/exec" import "time"
import "fmt"
import "log"
import "errors" // const (// {{{
// O_RDONLY int = syscall.O_RDONLY // open the file read-only.
// O_WRONLY int = syscall.O_WRONLY // open the file write-only.
// O_RDWR int = syscall.O_RDWR // open the file read-write.
// O_APPEND int = syscall.O_APPEND // append data to the file when writing.
// O_CREATE int = syscall.O_CREAT // create a new file if none exists.
// O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist
// O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
// O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
// )
//
// var (
// Stdin = newfile(uintptr(syscall.Stdin), "/dev/stdin")
// Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
// Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
// )
// }}}
const (
Unknown int = -
Dir int =
Regular int =
Symlink int =
Socket int =
NamedPipe int =
) var (
path string = "/tmp/link_to_testfile"
err error
) func main() {
defer defer_printBye() cwd, _ := os.Getwd()
fmt.Println("Work dir:", cwd)
os.Chdir("/tmp")
cwd, _ = os.Getwd()
fmt.Println("New work dir:", cwd) hostname, _ := os.Hostname()
pagesize := os.Getpagesize()
fmt.Printf("hostname = %s\npagesize = %d\n", hostname, pagesize) if nil != os.Setenv("HISTSIZE", "") {
log.Fatal("Can't set env HISTSIZE")
} fmt.Println(os.Getenv("HISTSIZE"))
os.Unsetenv("HISTSIZE")
fmt.Println("After Unsetenv:", os.Getenv("HISTSIZE")) //for _, env := range os.Environ() {
// fmt.Println(env)
//} os.Clearenv()
fmt.Println("Env variables after os.Clearenv: ", os.Environ()) groups, _ := os.Getgroups()
fmt.Println("groups IDs:", groups)
fmt.Println("uid:", os.Getuid(), "euid:", os.Geteuid(), "gid:", os.Getgid(), "egid:", os.Getegid(), "pid:", os.Getpid(), "ppid:", os.Getppid())
// {{{
/*
type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes for regular files; system-dependent for others
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // abbreviation for Mode().IsDir()
Sys() interface{} // underlying data source (can return nil)
} const (
// The single letters are the abbreviations used by the String method's formatting.
ModeDir FileMode = 1 << (32 - 1 - iota) // d: is a directory
ModeAppend // a: append-only
ModeExclusive // l: exclusive use
ModeTemporary // T: temporary file (not backed up)
ModeSymlink // L: symbolic link
ModeDevice // D: device file
ModeNamedPipe // p: named pipe (FIFO)
ModeSocket // S: Unix domain socket
ModeSetuid // u: setuid
ModeSetgid // g: setgid
ModeCharDevice // c: Unix character device, when ModeDevice is set
ModeSticky // t: sticky // Mask for the type bits. For regular files, none will be set.
ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice ModePerm FileMode = 0777 // Unix permission bits
)
*/ // }}} ftype, fm := file_info(path)
fmt.Println("File type is:", file_type_string(ftype)) fmt.Printf("permission: %s, %b\n", fm.String(), fm.Perm())
fm = fm &
os.Chmod(path, fm)
fmt.Printf("After os.Chmod, permission: %s, %b\n", fm.String(), fm.Perm()) err = os.Chown(path, , -)
print_err("Change owner to 1000/-1 failed!")
err = os.Lchown(path, , )
print_err("Change owner to 0/0 failed!")
os.Link(path, "tempfile_new")
os.Symlink(path, "tempfile_new_symlink")
os.Mkdir("/tmp/tempfile_dir", )
os.MkdirAll("/tmp/tempfile_dir_All/teem", ) out, _ := exec.Command("/bin/ls", "/tmp").Output()
fmt.Printf("%s", out)
fmt.Println() os.Rename("/tmp/tempfile_dir", "/tmp/tempfiledir")
os.Remove("/tmp/tempfiledir")
os.RemoveAll("/tmp/tempfile_dir_All")
fmt.Println("Delete all tmp files") out, _ = exec.Command("/bin/ls", "/tmp").Output()
fmt.Printf("%s", out)
fmt.Println() realname, _ := os.Readlink(path)
tmp0, _ := os.Stat(realname)
tmp1, _ := os.Stat(path)
if os.SameFile(tmp0, tmp1) {
fmt.Println("SameFile")
}
os.Truncate(path, )
fi, _ := os.Stat(path)
fmt.Println("New file size is:", fi.Size()) // type File struct {// {{{
// *file // os specific
// }
// }}}
fp, er := os.OpenFile("/tmp/xxxmyfile", os.O_CREATE|os.O_RDWR|os.O_TRUNC, )
err = er
print_err("Create /tmp/xxxmyfile failed!")
fp.Close()
os.Mkdir("/tmp/test", )
fp, _ = os.Open("/tmp/test")
fp.Chdir()
cwd, _ = os.Getwd()
fmt.Printf("Current dir:%s \n", cwd)
fp.Chmod()
fp.Chown(-, -)
fmt.Printf("%p, %s\n", fp.Fd(), fp.Name())
fr, fw, _ := os.Pipe()
in := []byte("aljkdflajs;lfjalsjfoawjlfkjaslkjflkashglhaklsjfjalsjfklasjklf") out = make([]byte, ) go gofn(fw, in) fr.Read(out)
fmt.Println(string(out)) go func() {
fw.WriteString("--------------------------------------------------------------")
fr.Read(out)
fmt.Println(string(out))
}() dirname, _ := fp.Readdirnames(-)
for _, yy := range dirname {
fmt.Printf("--------%s\n", yy)
} fp.Seek(, ) fii, _ := fp.Readdir(-)
for _, xx := range fii {
fmt.Printf("+++++++%s\n", xx.Name())
} // type Process struct {// {{{
// Pid int
// }
//
// type ProcAttr struct {
// Dir string
// Env []string
// Files []*File
// Sys *syscall.SysProcAttr
// }
//
// type ProcessState struct {}
// }}} pattr := os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}}
cmd := []string{"", "/tmp"} var ps *os.Process
go func() {
ps, _ = os.StartProcess("/bin/ls", cmd, &pattr)
}() go func() {
fmt.Println("Sleeping...3s...")
time.Sleep(time.Second * ) ps.Kill()
ps.Signal(os.Interrupt) }() fmt.Println("Sleeping...3s...")
time.Sleep(time.Second * ) procstat, _ := ps.Wait()
fmt.Println(procstat.String(), procstat.Exited(), procstat.Pid(), procstat.SystemTime(), procstat.UserTime()) fp.Close()
} func defer_printBye() {
fmt.Println("Bye, thanks for CPU time")
} func print_err(info string) {
if nil != err {
fmt.Fprintln(os.Stderr, errors.New(info))
}
} func file_info(path string) (int, os.FileMode) {
var ftype int
var fm os.FileMode fi, err := os.Lstat(path)
if nil != err {
switch {
case os.IsNotExist(err):
print_err("IsNotExist")
case os.IsPermission(err):
print_err("IsPermission")
default:
print_err("Unknown errors")
break
}
os.Exit()
} else {
switch fm = fi.Mode(); {
case fm.IsDir():
ftype = Dir
case fm&os.ModeSymlink != :
ftype = Symlink
case fm.IsRegular():
ftype = Regular
case fm&os.ModeSocket != :
ftype = Socket
case fm&os.ModeNamedPipe != :
ftype = NamedPipe
default:
ftype = Unknown
}
}
return ftype, fm
} func file_type_string(ftype int) string {
var res string
switch ftype {
case Dir:
res = "Dir"
case Regular:
res = "Regular"
case Socket:
res = "Socket"
case NamedPipe:
res = "NamedPipe"
case Unknown:
res = "Unknown"
default:
res = "Symlink"
}
return res
} func gofn(fw *os.File, in []byte) {
num, _ := fw.Write(in)
if num != len(in) {
print_err("write failed")
}
}
...