| // Copyright IBM Corp. 2014, 2026 | |
| // SPDX-License-Identifier: BUSL-1.1 | |
| package copy | |
| import ( | |
| "io" | |
| "os" | |
| ) | |
| // CopyFile copies the contents of the file named src to the file named | |
| // by dst. The file will be created if it does not already exist. If the | |
| // destination file exists, all it's contents will be replaced by the contents | |
| // of the source file. The file mode will be copied from the source and | |
| // the copied data is synced/flushed to stable storage. | |
| func CopyFile(src, dst string) (err error) { | |
| in, err := os.Open(src) | |
| if err != nil { | |
| return | |
| } | |
| defer in.Close() | |
| out, err := os.Create(dst) | |
| if err != nil { | |
| return | |
| } | |
| defer func() { | |
| if e := out.Close(); e != nil { | |
| err = e | |
| } | |
| }() | |
| _, err = io.Copy(out, in) | |
| if err != nil { | |
| return | |
| } | |
| err = out.Sync() | |
| if err != nil { | |
| return | |
| } | |
| si, err := os.Stat(src) | |
| if err != nil { | |
| return | |
| } | |
| err = os.Chmod(dst, si.Mode()) | |
| if err != nil { | |
| return | |
| } | |
| return | |
| } |