Files
2014-12-14 23:27:42 +08:00

154 lines
5.1 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 7.5 ファイルの操作
どのようなコンピュータ設備でもファイルは必要です。またWebプログラミングではファイルの操作はWebプログラマがよくぶつかる問題です。ファイルの操作はWebアプリケーションにおいて必須で、非常に有用です。我々はよくディレクトリ(フォルダ)の生成、ファイルの編集といった操作をすることになります。ここではGoによるこれらの操作をいくつかかいつまんで詳細に説明し、どのように使用するか実例をお見せします。
## ディレクトリの操作
ファイル操作の大部分の関数はどれもosパッケージにあります。以下にいくつかディレクトリの操作を行うものを挙げます
- func Mkdir(name string, perm FileMode) error
名前がnameのディレクトリを作成します。パーミッションの設定はpermで、例えば0777です。
- func MkdirAll(path string, perm FileMode) error
pathに従って階層的なサブディレクトリを作成します。たとえばastaxie/test1/test2です。
- func Remove(name string) error
名前がnameのディレクトリを削除します。ディレクトリにファイルまたはその他のディレクトリがある場合はエラーを発生させます。
- func RemoveAll(path string) error
pathに従って階層的なサブディレクトリを削除します。たとえばpathがあるひとつの名前であった場合、このディレクトリ以下のサブディレクトリが全て削除されます。
以下はコード例です:
package main
import (
"fmt"
"os"
)
func main() {
os.Mkdir("astaxie", 0777)
os.MkdirAll("astaxie/test1/test2", 0777)
err := os.Remove("astaxie")
if err != nil {
fmt.Println(err)
}
os.RemoveAll("astaxie")
}
## ファイルの操作
### 新規作成とファイルのオープン
ファイルを新規作成するには以下の2つのメソッドがあります
- func Create(name string) (file *File, err Error)
与えられたファイル名に従って新しいファイルを作成し、ファイルオブジェクトを返します。デフォルトでパーミッションは0666のファイルになります。返されたファイルオブジェクトは読み書きできます。
- func NewFile(fd uintptr, name string) *File
ファイルディスクリプタに従って対応するファイルを作成し、ファイルオブジェクトを返します。
以下の2つのメソッドによってファイルを開きます:
- func Open(name string) (file *File, err Error)
このメソッドは名前がnameのファイルを開きます。しかし読み込みしかできません。内部では実はOpenFileがコールされています。
- func OpenFile(name string, flag int, perm uint32) (file *File, err Error)
名前がnameのファイルを開きます。flagはオープンモードです。読み込むだけか、読み書きできるかといったものです。permはパーミッションです。
### ファイルへの書き込み
ファイルへの書き込みを行う関数:
- func (file *File) Write(b []byte) (n int, err Error)
byte型の情報をファイルに書き込みます。 
- func (file *File) WriteAt(b []byte, off int64) (n int, err Error)
指定した位置から開始してbyte型の情報を書き込みます。
- func (file *File) WriteString(s string) (ret int, err Error)
string情報をファイルに書き込みます。
ファイルへの書き込みを行うコード例
package main
import (
"fmt"
"os"
)
func main() {
userFile := "astaxie.txt"
fout, err := os.Create(userFile)
if err != nil {
fmt.Println(userFile, err)
return
}
defer fout.Close()
for i := 0; i < 10; i++ {
fout.WriteString("Just a test!\r\n")
fout.Write([]byte("Just a test!\r\n"))
}
}
### ファイルの読み込み
ファイルへの読み込みを行う関数:
- func (file *File) Read(b []byte) (n int, err Error)
データを読み取りbに渡します
- func (file *File) ReadAt(b []byte, off int64) (n int, err Error)
offから開始してデータを読み取りbに渡します
ファイルを読み取るコード例:
package main
import (
"fmt"
"os"
)
func main() {
userFile := "asatxie.txt"
fl, err := os.Open(userFile)
if err != nil {
fmt.Println(userFile, err)
return
}
defer fl.Close()
buf := make([]byte, 1024)
for {
n, _ := fl.Read(buf)
if 0 == n {
break
}
os.Stdout.Write(buf[:n])
}
}
### ファイルの削除
Go言語ではファイルの削除とディレクトリの削除は同じ関数で行われます
- func Remove(name string) Error
この関数をコールすることでファイル名がnameのファイルを削除できます
## links
* [目次](<preface.md>)
* 前へ: [テンプレートの処理](<07.4.md>)
* 次へ: [文字列の処理](<07.6.md>)