2012-09-13 4 views
6

키보드에서 입력을 가져 와서 텍스트 파일에 저장하려고하지만 실제로 어떻게해야하는지 혼란 스럽습니다.키보드에서 Golang의 파일로 입력을 시도하는 중

내 현재 코드는 순간 다음과 같다 :은 "운영 체제"와 "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 함수의 세 번째 인수가 무엇인지 혼동합니다. 문서에서는 "perm os.FileMode"유형에 대해 말하고 있지만, 프로그래밍에 익숙하지 않고 이동하기 때문에 나는 약간 우둔합니다.

아무도 절차를 수행하는 방법에 대한 조언이 없습니까? 나는이 컴파일하고 play.golang.org에서 실행,하지만 난 내 dev에 기계에 아니에요 확인했습니다 마리

예를 들어
+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") 
    } 
} 

사전에 감사합니다, 그래서 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

OP를 돕는 '0666'을 설명하는 것이 좋을 것 같습니다. –

+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을 참조하십시오.

이제 코드가 작동하므로 개선 할 수 있습니다. 열려있는 파일을 유지 대신 두 번 열어 예 : 파일, file.WriteString() APPEND하게 를 여는 동안 당신이 플래그 os.O_APPEND를 사용하는 것이

여기
// 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) 

마법. 을 열어 파일을 닫아야합니다.이 파일은 defer 키워드를 사용하여 함수가 존재 한 후에 수행합니다.

+0

코드 예제를 이용해 주셔서 감사합니다.이 문제를 이해하고 해결하는 방법을 알게되었습니다. – miner

관련 문제