『Golang』—— 标准库之 os
Posted 纯原创,零转载
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了『Golang』—— 标准库之 os相关的知识,希望对你有一定的参考价值。
Golang 的 os 库基本承袭 Unix 下 C 语言的用法
path 库:
func Base(path string) string //取文件名,不含目录部分 func Dir(path string) string //取路径中的目录名部分,不含文件名 func Join(elem ...string) string //拼接字段,中间自动添加 ‘/’
os 库:
1 ackage main 2 3 import "os" 4 import "os/exec" 5 6 import "time" 7 import "fmt" 8 import "log" 9 import "errors" 10 11 // const (// {{{ 12 // O_RDONLY int = syscall.O_RDONLY // open the file read-only. 13 // O_WRONLY int = syscall.O_WRONLY // open the file write-only. 14 // O_RDWR int = syscall.O_RDWR // open the file read-write. 15 // O_APPEND int = syscall.O_APPEND // append data to the file when writing. 16 // O_CREATE int = syscall.O_CREAT // create a new file if none exists. 17 // O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist 18 // O_SYNC int = syscall.O_SYNC // open for synchronous I/O. 19 // O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened. 20 // ) 21 // 22 // var ( 23 // stdin = newfile(uintptr(syscall.stdin), "/dev/stdin") 24 // Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") 25 // Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") 26 // ) 27 // }}} 28 const ( 29 Unknown int = -1 30 Dir int = 0 31 Regular int = 1 32 Symlink int = 2 33 Socket int = 3 34 NamedPipe int = 4 35 ) 36 37 var ( 38 path string = "/tmp/link_to_testfile" 39 err error 40 ) 41 42 func main() { 43 defer defer_printBye() 44 45 cwd, _ := os.Getwd() 46 fmt.Println("Work dir:", cwd) 47 os.Chdir("/tmp") 48 cwd, _ = os.Getwd() 49 fmt.Println("New work dir:", cwd) 50 51 hostname, _ := os.Hostname() 52 pagesize := os.Getpagesize() 53 fmt.Printf("hostname = %s\npagesize = %d\n", hostname, pagesize) 54 55 if nil != os.Setenv("HISTSIZE", "1000") { 56 log.Fatal("Can‘t set env HISTSIZE") 57 } 58 59 fmt.Println(os.Getenv("HISTSIZE")) 60 os.Unsetenv("HISTSIZE") 61 fmt.Println("After Unsetenv:", os.Getenv("HISTSIZE")) 62 63 //for _, env := range os.Environ() { 64 // fmt.Println(env) 65 //} 66 67 os.Clearenv() 68 fmt.Println("Env variables after os.Clearenv: ", os.Environ()) 69 70 groups, _ := os.Getgroups() 71 fmt.Println("groups IDs:", groups) 72 fmt.Println("uid:", os.Getuid(), "euid:", os.Geteuid(), "gid:", os.Getgid(), "egid:", os.Getegid(), "pid:", os.Getpid(), "ppid:", os.Getppid()) 73 // {{{ 74 /* 75 type FileInfo interface { 76 Name() string // base name of the file 77 Size() int64 // length in bytes for regular files; system-dependent for others 78 Mode() FileMode // file mode bits 79 ModTime() time.Time // modification time 80 IsDir() bool // abbreviation for Mode().IsDir() 81 Sys() interface{} // underlying data source (can return nil) 82 } 83 84 const ( 85 // The single letters are the abbreviations used by the String method‘s formatting. 86 ModeDir FileMode = 1 << (32 - 1 - iota) // d: is a directory 87 ModeAppend // a: append-only 88 ModeExclusive // l: exclusive use 89 ModeTemporary // T: temporary file (not backed up) 90 ModeSymlink // L: symbolic link 91 ModeDevice // D: device file 92 ModeNamedPipe // p: named pipe (FIFO) 93 ModeSocket // S: Unix domain socket 94 ModeSetuid // u: setuid 95 ModeSetgid // g: setgid 96 ModeCharDevice // c: Unix character device, when ModeDevice is set 97 ModeSticky // t: sticky 98 99 // Mask for the type bits. For regular files, none will be set. 100 ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice 101 102 ModePerm FileMode = 0777 // Unix permission bits 103 ) 104 */ // }}} 105 106 ftype, fm := file_info(path) 107 fmt.Println("File type is:", file_type_string(ftype)) 108 109 fmt.Printf("permission: %s, %b\n", fm.String(), fm.Perm()) 110 fm = fm & 0400 111 os.Chmod(path, fm) 112 fmt.Printf("After os.Chmod, permission: %s, %b\n", fm.String(), fm.Perm()) 113 114 err = os.Chown(path, 1000, -1) 115 print_err("Change owner to 1000/-1 failed!") 116 err = os.Lchown(path, 0, 0) 117 print_err("Change owner to 0/0 failed!") 118 os.Link(path, "tempfile_new") 119 os.Symlink(path, "tempfile_new_symlink") 120 os.Mkdir("/tmp/tempfile_dir", 0755) 121 os.MkdirAll("/tmp/tempfile_dir_All/teem", 0755) 122 123 out, _ := exec.Command("/bin/ls", "/tmp").Output() 124 fmt.Printf("%s", out) 125 fmt.Println() 126 127 os.Rename("/tmp/tempfile_dir", "/tmp/tempfiledir") 128 os.Remove("/tmp/tempfiledir") 129 os.RemoveAll("/tmp/tempfile_dir_All") 130 fmt.Println("Delete all tmp files") 131 132 out, _ = exec.Command("/bin/ls", "/tmp").Output() 133 fmt.Printf("%s", out) 134 fmt.Println() 135 136 realname, _ := os.Readlink(path) 137 tmp0, _ := os.Stat(realname) 138 tmp1, _ := os.Stat(path) 139 if os.SameFile(tmp0, tmp1) { 140 fmt.Println("SameFile") 141 } 142 os.Truncate(path, 1024) 143 fi, _ := os.Stat(path) 144 fmt.Println("New file size is:", fi.Size()) 145 146 // type File struct {// {{{ 147 // *file // os specific 148 // } 149 // }}} 150 fp, er := os.OpenFile("/tmp/xxxmyfile", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644) 151 err = er 152 print_err("Create /tmp/xxxmyfile failed!") 153 fp.Close() 154 os.Mkdir("/tmp/test", 0700) 155 fp, _ = os.Open("/tmp/test") 156 fp.Chdir() 157 cwd, _ = os.Getwd() 158 fmt.Printf("Current dir:%s \n", cwd) 159 fp.Chmod(0700) 160 fp.Chown(-1, -1) 161 fmt.Printf("%p, %s\n", fp.Fd(), fp.Name()) 162 fr, fw, _ := os.Pipe() 163 in := []byte("aljkdflajs;lfjalsjfoawjlfkjaslkjflkashglhaklsjfjalsjfklasjklf") 164 165 out = make([]byte, 100) 166 167 go gofn(fw, in) 168 169 fr.Read(out) 170 fmt.Println(string(out)) 171 172 go func() { 173 fw.WriteString("--------------------------------------------------------------") 174 fr.Read(out) 175 fmt.Println(string(out)) 176 }() 177 178 dirname, _ := fp.Readdirnames(-1) 179 for _, yy := range dirname { 180 fmt.Printf("--------%s\n", yy) 181 } 182 183 fp.Seek(0, 0) 184 185 fii, _ := fp.Readdir(-1) 186 for _, xx := range fii { 187 fmt.Printf("+++++++%s\n", xx.Name()) 188 } 189 190 // type Process struct {// {{{ 191 // Pid int 192 // } 193 // 194 // type ProcAttr struct { 195 // Dir string 196 // Env []string 197 // Files []*File 198 // Sys *syscall.SysProcAttr 199 // } 200 // 201 // type ProcessState struct {} 202 // }}} 203 204 pattr := os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}} 205 cmd := []string{"", "/tmp"} 206 207 var ps *os.Process 208 go func() { 209 ps, _ = os.StartProcess("/bin/ls", cmd, &pattr) 210 }() 211 212 go func() { 213 fmt.Println("Sleeping...3s...") 214 time.Sleep(time.Second * 3) 215 216 ps.Kill() 217 ps.Signal(os.Interrupt) 218 219 }() 220 221 fmt.Println("Sleeping...3s...") 222 time.Sleep(time.Second * 3) 223 224 procstat, _ := ps.Wait() 225 fmt.Println(procstat.String(), procstat.Exited(), procstat.Pid(), procstat.SystemTime(), procstat.UserTime()) 226 227 fp.Close() 228 } 229 230 func defer_printBye() { 231 fmt.Println("Bye, thanks for CPU time") 232 } 233 234 func print_err(info string) { 235 if nil != err { 236 fmt.Fprintln(os.Stderr, errors.New(info)) 237 } 238 } 239 240 func file_info(path string) (int, os.FileMode) { 241 var ftype int 242 var fm os.FileMode 243 244 fi, err := os.Lstat(path) 245 if nil != err { 246 switch { 247 case os.IsNotExist(err): 248 print_err("IsNotExist") 249 case os.IsPermission(err): 250 print_err("IsPermission") 251 default: 252 print_err("Unknown errors") 253 break 254 } 255 os.Exit(1) 256 } else { 257 switch fm = fi.Mode(); { 258 case fm.IsDir(): 259 ftype = Dir 260 case fm&os.ModeSymlink != 0: 261 ftype = Symlink 262 case fm.IsRegular(): 263 ftype = Regular 264 case fm&os.ModeSocket != 0: 265 ftype = Socket 266 case fm&os.ModeNamedPipe != 0: 267 ftype = NamedPipe 268 default: 269 ftype = Unknown 270 } 271 } 272 return ftype, fm 273 } 274 275 func file_type_string(ftype int) string { 276 var res string 277 switch ftype { 278 case Dir: 279 res = "Dir" 280 case Regular: 281 res = "Regular" 282 case Socket: 283 res = "Socket" 284 case NamedPipe: 285 res = "NamedPipe" 286 case Unknown: 287 res = "Unknown" 288 default: 289 res = "Symlink" 290 } 291 return res 292 } 293 294 func gofn(fw *os.File, in []byte) { 295 num, _ := fw.Write(in) 296 if num != len(in) { 297 print_err("write failed") 298 } 299 }
...
以上是关于『Golang』—— 标准库之 os的主要内容,如果未能解决你的问题,请参考以下文章