打开文件,写一些字,然后阅读,一无所获 [英] Open a file and write some word then read it get nothing

查看:38
本文介绍了打开文件,写一些字,然后阅读,一无所获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码是这样的.我可以正确运行代码.读取文件时,什么也没得到

The code is like this. I can run the code with no error.when reading file,can‘t get anything

    file,err := os.OpenFile("writeAt.txt",os.O_CREATE|os.O_APPEND|os.O_RDWR,777)
    if err != nil{
        panic(err)
    }
    fmt.Println(file)
    reader := bytes.NewReader([]byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"))
    _,err = reader.WriteTo(file)
    if err != nil{
        panic(err)
    }
    fmt.Println(file)
    reader = bytes.NewReader([]byte("bbbbbbbbbbbbbbbbbbbb\n"))
    _,err = reader.WriteTo(file)
    if err != nil{
        panic(err)
    }
    writer := bufio.NewWriter(os.Stdout)
    n,err := writer.ReadFrom(file)
    if err != nil{
        panic(err)
    }
    fmt.Println("n",n)

推荐答案

打开文件并对其进行写入时,文件指针(确定发生读取和写入的位置)会不断增加,因此下一次写入始终会写入到文件中.结尾.没有单独的读取"消息.和写入"指针,只有一个指针可以进行​​读取和写入.写完东西后,您必须倒带"一个字样.如果要读取刚刚写入文件的内容,则指向开始的指针.

When you open a file and write to it, the file pointer (that determines where reads and writes occur) is continuously incremented so the next write always writes to the end. There is no separate "read" and "write" pointer, there's a single pointer where reads and writes happen. After you write something, you have to "rewind" the pointer to the beginning if you want to read what you just wrote to the file.

这意味着在写之后尝试读取将不会读取任何内容,因为文件指针指向文件的末尾.关闭并重新打开文件会将指针指向文件的开头,这就是为什么您在重新打开后成功读取文件的原因.

This means that attempting to read after the writes will read nothing as the file pointer points to the end of the file. Closing and reopening the file positions the pointer to the beginning of the file, that's why you succeed reading it after reopening.

要在不重新打开的情况下阅读书面内容,请使用 File.Seek() .

To read the written content without reopening, set the pointer to the beginning of the file using File.Seek().

例如:

if _, err := file.Seek(0, io.SeekStart); err != nil {
    log.Printf("Failed to seek: %v", err)
}

// Now you can read content written to it previosly

还有一件更重要的事情.引用 File.Seek():

Also one more important thing. Quoting from File.Seek():

未指定使用O_APPEND打开的文件上Seek的行为.

The behavior of Seek on a file opened with O_APPEND is not specified.

由于确实使用 O_APPEND 打开文件,因此上述操作可能成功也可能不会成功.因此,如果您想重新阅读书面内容,请不要使用 O_APPEND .或者,如果必须使用 O_APPEND ,则必须重新打开文件.

Since you do open your file with O_APPEND, the above may or may not succeed. So do not use O_APPEND if you wish to re-read the written content. Or if you must use O_APPEND, then you must reopen the file.

这篇关于打开文件,写一些字,然后阅读,一无所获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆