我一直在尝试自己学习Go,但在尝试读取和写入普通文件时,我被难住了。

我可以到inFile, _:= os。Open(INFILE, 0,0),但实际上获取文件的内容没有意义,因为read函数以[]字节作为参数。

func (file *File) Read(b []byte) (n int, err Error)

当前回答

新方法

从Go 1.16开始,使用os。ReadFile将文件加载到内存中,并使用os。从内存写入文件的WriteFile (ioutil。ReadFile现在调用os。ReadFile,已弃用)。

小心操作系统。因为它将整个文件读入内存。

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    // `b` contains everything your file has.
    // This writes it to the Standard Out.
    os.Stdout.Write(b)

    // You can also write it to a file as a whole.
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

其他回答

看看文档,似乎你应该声明一个类型为[]字节的缓冲区,并将其传递给read,然后读取到这么多字符,并返回实际读取的字符数(和一个错误)。

医生说

Read从文件中读取最多len(b)个字节。它返回读取的字节数和一个Error(如果有的话)。EOF的信号是一个零计数,err设置为EOF。

这样不行吗?

编辑:另外,我认为你可能应该使用bufio包中声明的Reader/Writer接口,而不是使用os包。

请注意。由于Go 1.16 ReadFile在os包中。

试试这个:

package main

import (
  "io"; 
  )
  

func main() {
  contents,_ := io.ReadFile("filename");
  println(string(contents));
  io.WriteFile("filename", contents, 0644);
}

Read方法接受一个字节参数,因为这是它将读入的缓冲区。这是某些圈子里的常用成语,仔细想想还是有道理的。

通过这种方式,您可以确定读取器将读取多少字节,并检查返回值以查看实际读取了多少字节,并适当地处理任何错误。

正如其他人在他们的回答中指出的那样,bufio可能是您从大多数文件读取所需要的。

我再加一个提示,因为它真的很有用。从文件中读取一行的最好方法不是使用ReadLine方法,而是使用ReadBytes或ReadString方法。

使用io。复制

package main

import (
    "io"
    "log"
    "os"
)

func main () {
    // open files r and w
    r, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    defer r.Close()

    w, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    defer w.Close()

    // do the actual work
    n, err := io.Copy(w, r)
    if err != nil {
        panic(err)
    }
    log.Printf("Copied %v bytes\n", n)
}

如果你不想重新发明轮子,io。复制和io。CopyN可以为您服务。如果你检查io的来源。复制函数,它只是打包在Go库中的Mostafa的解决方案之一(实际上是“基本的”解决方案)。不过,他们使用的缓冲区比他大得多。

新方法

从Go 1.16开始,使用os。ReadFile将文件加载到内存中,并使用os。从内存写入文件的WriteFile (ioutil。ReadFile现在调用os。ReadFile,已弃用)。

小心操作系统。因为它将整个文件读入内存。

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    // `b` contains everything your file has.
    // This writes it to the Standard Out.
    os.Stdout.Write(b)

    // You can also write it to a file as a whole.
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}