Make a backup file: Difference between revisions
→{{header|Go}}: modify to require existing file
(Go solution) |
(→{{header|Go}}: modify to require existing file) |
||
Line 51:
bx := ".backup"
// see if it's a link
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
// stat to preserve permissions.
// attemp rename
▲ return
▲ }
} else {▼
▲ fmt.Println(err)
return▼
}▼
}
// create new file
err
if err != nil {
fmt.Println(err)
Line 92 ⟶ 83:
func main() {
err := updateWithBackup("myth", ".backup",
if _, err = f.Seek(0, os.SEEK_SET); err != nil {▼
return▼
▲ if err = f.Truncate(0); err != nil {
_, err = f.WriteString("you too!\n")▼
return
}
▲ return
if err != nil {
fmt.Println(err)
Line 112 ⟶ 102:
// update the file as needed and return any error, but should not close
// the file. updateWithBackup will then close the file and return any error.
func updateWithBackup(fn, bx string,
var f *os.File
if f, err = openWithBackup(fn, bx
return
}
Line 130 ⟶ 119:
// destination file + bx. Any error encountered is returned. tf will be
// an open file if and only if err == nil.
func openWithBackup(fn, bx string
// follow symlink.
if target, err := os.Readlink(fn); err == nil {
Line 137 ⟶ 126:
// open the target file for exclusive access.
if tf, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
▲ }
}
// deferred function closes target file if an error happens
// during the backup operation.
|