Golang文件IO 一
Golang文件IO 一
文件IO編程最基本、最常用的就屬讀寫文件操作了。ioutil包實現了一些IO實用功能,其中就包括非常簡捷、好用的文件讀取功能。
ioutil包有7個函數1個變量:
var Discard io.Writer = devNull(0)
func NopCloser(r io.Reader) io.ReadCloser
func ReadAll(r io.Reader) ([]byte, error)
func ReadDir(dirname string) ([]os.FileInfo, error)
func ReadFile(filename string) ([]byte, error)
func TempDir(dir, prefix string) (name string, err error)
func TempFile(dir, prefix string) (f *os.File, err error)
func WriteFile(filename string, data []byte, perm os.FileMode) error
ReadFile和WriteFile這兩個函數分別實現了讀文件和寫文件操作,一行代碼即可搞定,非常便捷。
func ReadFile(filename string) ([]byte, error)
ReadFile讀取filename
func WriteFile(filename string, data []byte, perm os.FileMode) error
WriteFile將data寫入到filename指定的文件。如果文件不存在,WriteFile用權限perm創建文件;如果文件存在,WriteFile函數在寫之前先將文件截斷。
可以搭配json包實現程序配置的讀寫功能。下面是一個讀寫數據庫配置的例子。
package main import ( "fmt" "io/ioutil" "log" "encoding/json" ) type AppConf struct{ DriverName string `json:"driver_name"` SqlUser string `json:"sql_user"` SqlPass string `json:"sql_password"` SqlUrls string `json:"sql_urls"` SqlDB string `json:"sql_db"` } func main() { appConf := AppConf{DriverName:"mysql", SqlUser:"root", SqlPass:"password", SqlUrls:"tcp(127.0.0.1:3306)", SqlDB:"mydb"} bConf,err := json.MarshalIndent(appConf,"","\t") if err != nil { log.Fatal(err) } err = ioutil.WriteFile("app.cfg",bConf,0666) if err != nil { log.Fatal(err) } var appConf2 AppConf bConf,err =ioutil.ReadFile("app.cfg") if err != nil { log.Fatal(err) } err = json.Unmarshal(bConf,&appConf2) if err != nil { log.Fatal(err) } fmt.Println("appConf === appConf2",appConf==appConf2) }
運行結果如下:
生成的app.cfg內容如下:
{ "driver_name": "mysql", "sql_user": "root", "sql_password": "password", "sql_urls": "tcp(127.0.0.1:3306)", "sql_db": "mydb" }
通常WriteFile的權限是0666。關於權限的定義,可以查看golang源碼(C:\Go\src\os\types.go)
// A FileMode represents a file‘s mode and permission bits. // The bits have the same definition on all systems, so that // information about files can be moved from one system // to another portably. Not all bits apply to all systems. // The only required bit is ModeDir for directories. type FileMode uint32 // The defined file mode bits are the most significant bits of the FileMode. // The nine least-significant bits are the standard Unix rwxrwxrwx permissions. // The values of these bits should be considered part of the public API and // may be used in wire protocols or disk representations: they must not be // changed, although new bits might be added. 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; Plan 9 only 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 )
FileMode在所有系統種的定義相同,與linux系統的權限定義類似,一些可取的值包括如下:
const ( OS_READ = 04 OS_WRITE = 02 OS_EX = 01 OS_USER_SHIFT = 6 OS_GROUP_SHIFT = 3 OS_OTH_SHIFT = 0 OS_USER_R = OS_READ<<OS_USER_SHIFT OS_USER_W = OS_WRITE<<OS_USER_SHIFT OS_USER_X = OS_EX<<OS_USER_SHIFT OS_USER_RW = OS_USER_R | OS_USER_W OS_USER_RWX = OS_USER_RW | OS_USER_X OS_GROUP_R = OS_READ<<OS_GROUP_SHIFT OS_GROUP_W = OS_WRITE<<OS_GROUP_SHIFT OS_GROUP_X = OS_EX<<OS_GROUP_SHIFT OS_GROUP_RW = OS_GROUP_R | OS_GROUP_W OS_GROUP_RWX = OS_GROUP_RW | OS_GROUP_X OS_OTH_R = OS_READ<<OS_OTH_SHIFT OS_OTH_W = OS_WRITE<<OS_OTH_SHIFT OS_OTH_X = OS_EX<<OS_OTH_SHIFT OS_OTH_RW = OS_OTH_R | OS_OTH_W OS_OTH_RWX = OS_OTH_RW | OS_OTH_X OS_ALL_R = OS_USER_R | OS_GROUP_R | OS_OTH_R OS_ALL_W = OS_USER_W | OS_GROUP_W | OS_OTH_W OS_ALL_X = OS_USER_X | OS_GROUP_X | OS_OTH_X OS_ALL_RW = OS_ALL_R | OS_ALL_W OS_ALL_RWX = OS_ALL_RW | OS_GROUP_X)
WriteFile權限指定為0777,Ubuntu上執行上面的例子,查看app.cfg的詳細信息
dell@dell-VirtualBox:~/mygo/src/example/ioutil$ ll app.cfg -rwxrwxr-x 1 dell dell 132 11月 21 22:15 app.cfg*
WriteFile 權限指定為0666,Ubuntu上執行上面的例子,查看app.cfg的詳細信息
dell@dell-VirtualBox:~/mygo/src/example/ioutil$ ll app.cfg -rw-rw-r-- 1 dell dell 132 11月 21 22:18 app.cfg
Golang文件IO 一