douzhi1919 2018-06-07 12:11
浏览 391
已采纳

使用Go将文件移动到其他驱动器

I'm trying to move a file from my C-drive to my H-drive using os.Replace().

The code looks as follows:

func MoveFile(source string, destination string) {
    err := os.Rename(source, destination)
    if err != nil {
        fmt.Println(err)
    }
}

However, when I run the code I get the following error:

rename C:\old\path\to\file.txt H:
ew\path\to\file.txt: The system cannot move the file to a different disk drive.

I found this issue on GitHub that specifies the problem but it appears that they will not change this function to allow it to move file on different disk drives.

I already searched for other possibilities to move files, but found nothing in the standard documentation or the internet.

So, what should I do now to be able to move files on different disk drives?

  • 写回答

2条回答 默认 最新

  • duanlinghe8417 2018-06-07 13:00
    关注

    As the comment said, you'll need to create a new file on the other disk, copy the contents, and then remove the original. It's straightforward using os.Create, io.Copy, and os.Remove:

    import (
        "fmt"
        "io"
        "os"
    )
    
    func MoveFile(sourcePath, destPath string) error {
        inputFile, err := os.Open(sourcePath)
        if err != nil {
            return fmt.Errorf("Couldn't open source file: %s", err)
        }
        outputFile, err := os.Create(destPath)
        if err != nil {
            inputFile.Close()
            return fmt.Errorf("Couldn't open dest file: %s", err)
        }
        defer outputFile.Close()
        _, err = io.Copy(outputFile, inputFile)
        inputFile.Close()
        if err != nil {
            return fmt.Errorf("Writing to output file failed: %s", err)
        }
        // The copy was successful, so now delete the original file
        err = os.Remove(sourcePath)
        if err != nil {
            return fmt.Errorf("Failed removing original file: %s", err)
        }
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类