2012-09-13 11 views
6

キーボードから入力してテキストファイルに保存しようとしていますが、実際にそれを行う方法はちょっと混乱しています。キーボードからGolangのファイルに入力を書き込もうとしています

私の現在のコードは、現時点では次の通りである:「OS」と「IO」のパッケージで非常に多くの機能があります

// reads the file txt.txt 
bs, err := ioutil.ReadFile("text.txt") 
if err != nil { 
     panic(err) 
} 

// Prints out content 
textInFile := string(bs) 
fmt.Println(textInFile) 

// Standard input from keyboard 
var userInput string 
fmt.Scanln(&userInput) 

//Now I want to write input back to file text.txt 
//func WriteFile(filename string, data []byte, perm os.FileMode) error 

inputData := make([]byte, len(userInput)) 

err := ioutil.WriteFile("text.txt", inputData,) 

。私はこの目的のために実際に使用すべきものについては非常に混乱しています。

また、WriteFile関数の第3引数が何であるべきかについても混乱しています。ドキュメントには "perm os.FileMode"というタイプが書かれていますが、私はプログラミングや新しくなって以来、私はちょっと無礼です。

誰も手技の方法に関するヒントはありますか?たとえば、事前に おかげで、 マリー

+1

新しいユーザー入力をファイルの末尾に追加するか、古いファイルを新しい入力に置き換えますか? – matthias

+0

ファイルの末尾に追加します。 – miner

+3

[this](http://en.wikipedia.org/wiki/Filesystem_permissions#Traditional_Unix_permissions)は、一部の機能で必要とされるアクセス許可を理解するのに役立ちます。 0666は、ファイルがすべての人(ユーザ、彼のグループ、世界)によって読み書き可能でなければならないことを(8進形式で)意味します。 –

答えて

2
// reads the file txt.txt 
bs, err := ioutil.ReadFile("text.txt") 
if err != nil { //may want logic to create the file if it doesn't exist 
     panic(err) 
} 

var userInput []string 

var err error = nil 
var n int 
//read in multiple lines from user input 
//until user enters the EOF char 
for ln := ""; err == nil; n, err = fmt.Scanln(ln) { 
    if n > 0 { //we actually read something into the string 
     userInput = append(userInput, ln) 
    } //if we didn't read anything, err is probably set 
} 

//open the file to append to it 
//0666 corresponds to unix perms rw-rw-rw-, 
//which means anyone can read or write it 
out, err := os.OpenFile("text.txt", os.O_APPEND, 0666) 
defer out.Close() //we'll close this file as we leave scope, no matter what 

if err != nil { //assuming the file didn't somehow break 
    //write each of the user input lines followed by a newline 
    for _, outLn := range userInput { 
     io.WriteString(out, outLn+"\n") 
    } 
} 

は、私は、これはコンパイルしplay.golang.org上で動作を確認しましたが、私は私のdevのマシンではありませんよ私はそれがStdinとファイルと完全に正しく相互作用していることを確認することはできません。これはあなたがしかし始まったはずです。

+0

ありがとう、本当に助けてくれました! – miner

3

package main 

import (
    "fmt" 
    "io/ioutil" 
    "os" 
) 

func main() { 
    fname := "text.txt" 

    // print text file 
    textin, err := ioutil.ReadFile(fname) 
    if err == nil { 
     fmt.Println(string(textin)) 
    } 

    // append text to file 
    f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666) 
    if err != nil { 
     panic(err) 
    } 
    var textout string 
    fmt.Scanln(&textout) 
    _, err = f.Write([]byte(textout)) 
    if err != nil { 
     panic(err) 
    } 
    f.Close() 

    // print text file 
    textin, err = ioutil.ReadFile(fname) 
    if err != nil { 
     panic(err) 
    } 
    fmt.Println(string(textin)) 
} 
+2

私は '0666'がOPに役立つと説明していると思います。 –

+2

ここで説明したり、答えたり、解決したりしていますか?待って、答えないで!私はすでにそれを見ることができます。 – Kissaki

2

単純にユーザーの入力をテキストファイルに追加したい場合は、入力したとおりに の入力を読み取ってから、ioutil.WriteFileを使用します。 あなたはすでに正しいアイデアを得ています。

あなたの道を行くようにするには、単純化されたソリューションは、このようになります:

// Read old text 
current, err := ioutil.ReadFile("text.txt") 

// Standard input from keyboard 
var userInput string 
fmt.Scanln(&userInput) 

// Append the new input to the old using builtin `append` 
newContent := append(current, []byte(userInput)...) 

// Now write the input back to file text.txt 
err = ioutil.WriteFile("text.txt", newContent, 0666) 

WriteFileの最後のパラメータは ファイルのためのさまざまなオプションを指定するフラグです。上位ビットはファイルタイプ(たとえば、os.ModeDir)のようなオプションで、下位の数字はUNIXアクセス権の形式でのアクセス許可を表します(0666、8進形式では、ユーザーrw、グループrw、その他rwを表します)。詳細はthe documentationを参照してください。

コードが機能したら、改善することができます。代わりに、それを2回開くの 開いているファイルを保持することによってたとえば:

// Open the file for read and write (O_RDRW), append to it if it has 
// content, create it if it does not exit, use 0666 for permissions 
// on creation. 
file, err := os.OpenFile("text.txt", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) 

// Close the file when the surrounding function exists 
defer file.Close() 

// Read old content 
current, err := ioutil.ReadAll(file) 

// Do something with that old content, for example, print it 
fmt.Println(string(current)) 

// Standard input from keyboard 
var userInput string 
fmt.Scanln(&userInput) 

// Now write the input back to file text.txt 
_, err = file.WriteString(userInput) 

ここで魔法がfile.WriteString()追記を行い、ファイル、 を開いているときにフラグos.O_APPENDを使用すること、です。 を開いた後でファイルを閉じる必要があることに注意してください。これは、関数が存在した後にdeferキーワードを使用して行います。

+0

コード例をありがとう、本当に私はこの問題とそれを解決する方法を理解するのに役立ちました。 – miner

関連する問題