如何在Go中将整个字符串保存为txt文件?

时间:2015-06-19 20:24:17

标签: string go

我正在Go中创建一个简单的文字处理程序。从命令行,我有两个提示:

$输入标题:

$ Enter Body:

程序应该将文档保存为txt文件并将其打印到命令行。如果用户用户键入单字标题和单字体,则该程序有效。但是如果用户输入多个单词的标题,就会发生这种情况:

$Enter Title: Here is a title

$Enter Body: s

$  title

-bash: title: command not found

这是我到目前为止的代码:

package main

import (
    "fmt"
    "io/ioutil"
)

//Create struct for a document
type Document struct {
    Title string
    Body []byte
}

//Save document as txt file
func (p *Document) save() error {
    filename := p.Title + ".txt"
    return ioutil.WriteFile(filename, p.Body, 0600)
}

//Load document
func loadPage(title string) (*Document, error) {
    filename := title + ".txt"
    body, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Document{Title: title, Body: body}, nil
}

//Input document title and body. 
func main() {
    fmt.Print("Enter Title: ")
    var Title string
    fmt.Scanln(&Title)

    fmt.Print("Enter Body: ")
    var Body []byte
    fmt.Scanln(&Body)

//Save document and display on command line
    p1 := &Document{Title: Title, Body: []byte(Body)}
    p1.save()
    p2, _ := loadPage(Title)
    fmt.Println(string(p2.Body))
}

1 个答案:

答案 0 :(得分:0)

使用bufio.ReadString代替fmt.Scanln怎么样? 不是100%Scanln如何工作,但我很确定这个问题来自滥用该功能。 bufio示例:

package main

import (
        "bufio"
        "fmt"
        "io/ioutil"
        "log"
        "os"
        "strings"
)

// Document represent the document's data.
type Document struct {
        Title string
        Body  []byte
}

// Save dumps document as txt file on disc.
func (p *Document) save() error {
        filename := p.Title + ".txt"
        return ioutil.WriteFile(filename, p.Body, 0600)
}

// loadPage loads a document from disc.
func loadPage(title string) (*Document, error) {
        filename := title + ".txt"
        body, err := ioutil.ReadFile(filename)
        if err != nil {
                return nil, err
        }
        return &Document{Title: title, Body: body}, nil
}

// Input document title and body.
func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter Title: ")
        title, err := reader.ReadString('\n')
        if err != nil {
                log.Fatal(err)
        }
        title = strings.TrimSpace(title)

        fmt.Print("Enter Body: ")
        body, err := reader.ReadString('\n')
        if err != nil {
                log.Fatal(err)
        }
        body = strings.TrimSpace(body)

        //Save document and display on command line
        p1 := &Document{Title: title, Body: []byte(body)}
        if err := p1.save(); err != nil {
                log.Fatal(err)
        }
        p2, err := loadPage(title)
        if err != nil {
                log.Fatal(err)
        }
        fmt.Println(string(p2.Body))
}