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 函数中的第三个参数应该是什么感到困惑。在文档中说“perm os.FileMode”类型,但由于我是编程新手,所以我有点无能为力。

有人对如何处理有任何提示吗?在此先感谢,玛丽

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 权限形式的权限(0666八进制格式,代表用户 rw、组 rw、其他 rw)。有关更多详细信息,请参阅文档

现在您的代码有效,我们可以改进它。例如,通过保持文件打开而不是打开两次:

// 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 回答