ioパッケージでのファイル書き込み
goのioパッケージにはOpenFile
という関数がある。これは、ファイル名、ファイルに対する操作、ファイルのPermissionを設定して、File構造体を作成する関数であうる。
io.OpenFile(filename string, flag int, permission int)
ファイルに対する操作
ファイルの操作には下記の通りである。
const ( // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. 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. // The remaining values may be or'ed in to control behavior. 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 // truncate regular writable file when opened. )
ここで、注目いたいのはO_RDONLY
、O_WRONRY
、O_RDWR
は必ず一つ選ぶ必要があると言うことである。
これら3つはファイルをどの様に開くかのみを定義している。
ファイルに書き込みを行いたい場合は別途O_APPEND
を呼び出す必要がある。
Permission
ここで指定するPermissionはLinuxなどのPermissionと同じ形式で指定する。