donglvhe7591 2013-09-29 16:40
浏览 38
已采纳

如何检测Golang中打开文件的文件名的更改

Using Go, I was writing a small utility that in part needs to notice if the filename of an open file changes. The below code illustrates the approach I tried:

package main

import "os"
import "fmt"
import "time"

func main() {

    path := "data.txt"
    file, _ := os.Open(path)

    for {
        details, _ := file.Stat()
        fmt.Println(details.Name())
        time.Sleep(5 * time.Second)
    }
}

This just starts an endless loop, running file.Stat() to obtain file details every 5 seconds and then printing out the name. However, despite changing the filename as this is running, the output of the above does not change.

replacing details.Name() with details.Size() does however notice changes to the filesize.

Is this simply a bug in my version of Go, or am I just doing things wrong? I cannot find mention of such an issue anywhere offhand.

I am running this on a Mac, with Go version 1.1.1 (darwin/amd64).

Thanks in advance for any replies :)

  • 写回答

2条回答 默认 最新

  • douyong8801 2013-09-29 19:55
    关注

    On Unix-like operating systems, once you open a file it is no longer tied to a name. The file-descripter you get is only tied to the inode of the file you open. All meta-data of a file is associated with the inode. There is no simple way to get the name of a file from the inode, thus what you want is impossible, except if the operating system you are using provides a special means to do that.

    Also: What filename do you want to observe? A file could have multiple names or no name at all (such as a typical temporary file).

    The only thing I think you could do is:

    • Open the file, remember the filename
    • periodically call Stat on the filename to see whether the inode matches
    • if the inode is different, your file has been moved

    This does however, not give you the new filename. Such a thing is impossible to do portably.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度