7

キーボードから入力を取得してテキストファイルに保存しようとしていますが、実際の方法について少し混乱しています。

私の現在のコードは現在次のとおりです。

// 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, )

「os」および「io」パッケージには非常に多くの関数があります。私はこの目的のために実際にどれを使うべきかについて非常に混乱しています。

また、WriteFile関数の3番目の引数がどうあるべきかについても混乱しています。ドキュメントには「permos.FileMode」タイプと書かれていますが、私はプログラミングとGoに慣れていないので、少し無知です。

誰かが手続きする方法について何かヒントがありますか?よろしくお願いします、マリー

4

3 に答える 3

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))
}
于 2012-09-13T16:30:00.950 に答える
3
// 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でコンパイルおよび実行されることを確認しましたが、開発マシンを使用していないため、Stdinおよびファイルと完全に正しく相互作用していることを確認できません。これで始められるはずです。

于 2012-09-13T16:55:26.487 に答える
3

ユーザーの入力をテキストファイルに追加したいだけの場合は、すでに行ったように入力を読み取り、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パーミッションの形式のパーミッションを表します(06668進形式では、ユーザーrw、グループrw、その他のrwを表します)。詳細については、ドキュメントを参照してください。

コードが機能するようになったので、コードを改善できます。たとえば、ファイルを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)

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

于 2012-09-13T19:18:55.520 に答える