Go file

2165 ワード

gaojie @Joy :/media/gaojie/Linux/Go/workspace/file$ tree
.
├── bin
│   └── file
├── src
│   ├── file.go
│   └── file.go~
└── tmp
file.goソースは以下の通りです.
package main

import (
	"os"
	"log"
)

func main(){
	if(len(os.Args) < 3){
		log.Fatal("Usage <command> <fileName> [data]");
	}
	log.Printf("args:%s
", os.Args); command := os.Args[1]; fileName := os.Args[2]; // file, err := os.Open(fileName); if err != nil { log.Println(err) file, err = os.Create(fileName); if(err != nil){ log.Fatal(err) } } // fileInfo, _ := file.Stat() log.Printf("name:%s, size:%d
", fileInfo.Name(), fileInfo.Size()); switch command { case "read": buf := make([]byte, fileInfo.Size()) readSize, _ := file.Read(buf) log.Printf("readSize:%d
", readSize) log.Print("bytes:%s
", string(buf)); case "write": if len(os.Args) != 4 { MsgExit("Usage: <command> <file> <data>") } data := os.Args[3]; writeSize, err := file.WriteString(data); if err == nil{ log.Printf("wirte sucess!%d
", writeSize) } } } func MsgExit( v ...interface{}){ //fatal , os.Exit(1) . log.Fatal(v) }

コンパイルと実行
go build -o bin/file src/file.go
gaojie@Joy:/media/gaojie/Linux/Go/workspace/file$ ./bin/file write tmp  gaojie
2013/10/05 15:20:53 args:[./bin/file write tmp gaojie]
2013/10/05 15:20:53 name:tmp, size:3
gaojie@Joy:/media/gaojie/Linux/Go/workspace/file$ ./bin/file read tmp 
2013/10/05 15:20:56 args:[./bin/file read tmp]
2013/10/05 15:20:56 name:tmp, size:3
2013/10/05 15:20:56 readSize:3
2013/10/05 15:20:56 bytes:%s
xxx