dqzg62440 2016-03-06 12:44
浏览 79

关闭文件,然后在golang中重命名

When I do some file operations with golang, I firstly open a file and add the close() into defer list, then I try to rename that file. If I close the file manually, the defer will close it again. If I wait for the defer to close it, the rename will cause error because it is not closed yey. Code as below

func main() {

    pfile1, _ := os.Open("myfile.log")
    defer pfile1.Close() //It will be closed again.
    ...
    ...
    pfile1.Close() //I have to close it before rename it.
    os.Rename("myfile.log", "myfile1.log")
}

I found some ugly solution, such as create another function to separate the open file, does any better solution that below?

func main() {

    var pfile1 *os.File
    ugly_solution(pfile1)

    os.Rename("myfile.log", "myfile1.log")
}

func ugly_solution(file *os.File) {
    file, _ = os.Open("myfile.log")
defer file.Close()
}
  • 写回答

3条回答 默认 最新

  • dseslyh6662605 2016-03-06 12:54
    关注

    There are a few things that are not clear to me about your code.

    First of all, why do you open the file before renaming it? This is not required by the os.Rename function. The function takes two strings representing the old and new file name, there is no need to pass a file pointer.

    func main() {
        ...
        ...
        os.Rename("myfile.log", "myfile1.log")
    }
    

    Assuming you need to make changes to the file content (which doesn't seem to be the case given the ugly_solution method) and you have to open the file, then why deferring file.Close()? You don't have to defer the method if you need it to be called explicitly somewhere in the same method. Simply call it.

    func main() {
        pfile1, _ := os.Open("myfile.log")
        ...
        ...
        pfile1.Close()
        os.Rename("myfile.log", "myfile1.log")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)