golang建立文字檔
f,err := os.Create(fileName) defer f.Close() if err !=nil { fmt.Println(err.Error()) } else { _,err=f.Write([]byte("要寫入的常值內容")) checkErr(err) }
golang讀取文字檔
f, err := os.OpenFile(fileName, os.O_RDONLY,0600) defer f.Close() if err !=nil { fmt.Println(err.Error()) } else { contentByte,err=ioutil.ReadAll(f) checkErr(err)fmt.Println(string(contentByte)) }
OpenFile用法:os.OpenFile(檔案名稱,開啟檔案,開啟模式)
//開啟檔案
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.)
//開啟模式
const (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 Unix 主機 socketModeSetuid // u: setuid 設定uidModeSetgid // g: setgid 設定gidModeCharDevice // c: Unix character device, when ModeDevice is set Unix 字元裝置,當裝置模式是設定UnixModeSticky // t: sticky 粘性的// Mask for the type bits. For regular files, none will be set. bit位遮蓋.不變的檔案設定為noneModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDeviceModePerm FileMode = 0777 // Unix permission bits 許可權位.)
golang寫入文字檔
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC,0600) defer f.Close() if err !=nil { fmt.Println(err.Error()) } else { _,err=f.Write([]byte("要寫入的常值內容")) checkErr(err) }