登录
首页 >  Golang >  Go问答

在 Go 中如何复制文件而不覆盖已存在的文件?

来源:stackoverflow

时间:2024-02-22 21:51:16 259浏览 收藏

本篇文章给大家分享《在 Go 中如何复制文件而不覆盖已存在的文件?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

如果文件存在,如何使用给定名称创建新文件

例如:如果 word_destination.txt 存在,则将内容复制到 word_destination(1).txt

如有任何帮助,我们将不胜感激...

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)


func main() {

    src := ./word_source.txt
    desti := ./folder/word_destination.txt

    //if file exists want to copy it to the word_destination(1).txt
    if _, err := os.Stat(desti); err == nil {
        // path/to/whatever exists
        fmt.Println("File Exists")

    } else {
        fmt.Println("File does not Exists")
        bytesRead, err := ioutil.ReadFile(src)

        if err != nil {
            log.Fatal(err)
        }

正确答案


func tryCopy(src, dst string) error {
    in, err := os.Open(src)
    if err != nil {
        return err
    }
    defer in.Close()

    out, err := os.OpenFile(dst, os.O_CREATE| os.O_EXCL, 0644)
    if err != nil {
        return err
    }
    defer out.Close()

    _, err = io.Copy(out, in)
    if err != nil {
        return err
    }
    return out.Close()
}
// ......
if _, err := os.Stat(desti); err == nil {
    // path/to/whatever exists
    fmt.Println("File Exists")
    for i := 1; ; i++ {
        ext := filepath.Ext(desti)
        newpath := fmt.Sprintf("%s(%d)%s", strings.TrimSuffix(desti, ext), i, ext)

        err := tryCopy(desti, newpath)
        if err == nil {
            break;
        }
        
        if os.IsExists(err) {
            continue;
        } else {
            return err;
        }
    }
}

今天关于《在 Go 中如何复制文件而不覆盖已存在的文件?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>