Make a backup file: Difference between revisions

Content added Content deleted
(Applesoft BASIC)
m (syntax highlighting fixup automation)
Line 17: Line 17:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V targetfile = ‘pycon-china’
<syntaxhighlight lang="11l">V targetfile = ‘pycon-china’
fs:rename(fs:path:canonical(targetfile), fs:path:canonical(targetfile)‘.bak’)
fs:rename(fs:path:canonical(targetfile), fs:path:canonical(targetfile)‘.bak’)
V f = File(fs:path:canonical(targetfile), ‘w’)
V f = File(fs:path:canonical(targetfile), ‘w’)
f.write(‘this task was solved during a talk about rosettacode at the PyCon China in 2011’)
f.write(‘this task was solved during a talk about rosettacode at the PyCon China in 2011’)
f.close()</lang>
f.close()</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
Due to all the pitfalls in this task it is helpful to turn on debugging by default. It is also helpful, to show each DOS 3.3 Command, by entering MON C before running the program. There is an extra PRINT statement in line 540 to work-around an issue with the display of DOS 3.3 commands after an error occurs. Setting ERASEANYBACKUP will delete the backup file if it already exists. Delete lines 180 to 230 with DEL 180,230 and it is possible with DOS 3.3 to have backup files all with the same name due to a pitfall in the RENAME Command.
Due to all the pitfalls in this task it is helpful to turn on debugging by default. It is also helpful, to show each DOS 3.3 Command, by entering MON C before running the program. There is an extra PRINT statement in line 540 to work-around an issue with the display of DOS 3.3 commands after an error occurs. Setting ERASEANYBACKUP will delete the backup file if it already exists. Delete lines 180 to 230 with DEL 180,230 and it is possible with DOS 3.3 to have backup files all with the same name due to a pitfall in the RENAME Command.
<lang gwbasic> 100 ERASEANYBACKUP = FALSE
<syntaxhighlight lang="gwbasic"> 100 ERASEANYBACKUP = FALSE
110 DEBUG = NOT FALSE
110 DEBUG = NOT FALSE
120 F$ = "FILE"
120 F$ = "FILE"
Line 62: Line 62:
540 PRINT
540 PRINT
550 IF DEBUG THEN PRINT " <<< "N$" DOES NOT EXIST."
550 IF DEBUG THEN PRINT " <<< "N$" DOES NOT EXIST."
560 RETURN</lang>
560 RETURN</syntaxhighlight>
<lang>DELETE FILE
<syntaxhighlight lang="text">DELETE FILE
DELETE BACKUP FILE
DELETE BACKUP FILE
MON C</lang>
MON C</syntaxhighlight>
<lang gwbasic>RUN</lang>
<syntaxhighlight lang="gwbasic">RUN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 76: Line 76:
CLOSE FILE
CLOSE FILE
</pre>
</pre>
<lang gwbasic>RUN</lang>
<syntaxhighlight lang="gwbasic">RUN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 90: Line 90:
CLOSE FILE
CLOSE FILE
</pre>
</pre>
<lang gwbasic>RUN</lang>
<syntaxhighlight lang="gwbasic">RUN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 101: Line 101:
</pre>
</pre>
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>targetfile := "ahk-file"
<syntaxhighlight lang="autohotkey">targetfile := "ahk-file"
if FileExist(targetfile)
if FileExist(targetfile)
FileMove, %targetfile%, %targetfile%.bak
FileMove, %targetfile%, %targetfile%.bak
Line 113: Line 113:
}
}
file.Write("This is a test string.`r`n")
file.Write("This is a test string.`r`n")
file.Close()</lang>
file.Close()</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAKE_A_BACKUP_FILE.AWK filename(s)
# syntax: GAWK -f MAKE_A_BACKUP_FILE.AWK filename(s)
# see: http://www.gnu.org/software/gawk/manual/gawk.html#Extension-Sample-Inplace
# see: http://www.gnu.org/software/gawk/manual/gawk.html#Extension-Sample-Inplace
Line 133: Line 133:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
Line 157: Line 157:
echo !line[1]!>"%filePath%"
echo !line[1]!>"%filePath%"
for /l %%i in (2,1,%i%) do echo !line[%%i]!>>"%filePath%"
for /l %%i in (2,1,%i%) do echo !line[%%i]!>>"%filePath%"
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Appends a version number and increments it on each backup
Appends a version number and increments it on each backup
<lang lisp>(defun parse-integer-quietly (&rest args)
<syntaxhighlight lang="lisp">(defun parse-integer-quietly (&rest args)
(ignore-errors (apply #'parse-integer args)))
(ignore-errors (apply #'parse-integer args)))


Line 179: Line 179:
(rename-file file (get-next-version file))
(rename-file file (get-next-version file))
(with-open-file (out file :direction :output)
(with-open-file (out file :direction :output)
(print data out))))</lang>
(print data out))))</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def backup_file(filename) do
def backup_file(filename) do
backup = filename <> ".backup"
backup = filename <> ".backup"
Line 193: Line 193:
end
end


hd(System.argv) |> RC.backup_file</lang>
hd(System.argv) |> RC.backup_file</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
===Rename===
===Rename===
This is the technique of the task description.
This is the technique of the task description.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 230: Line 230:
fmt.Println(err)
fmt.Println(err)
}
}
}</lang>
}</syntaxhighlight>
===Copy===
===Copy===
Alternative technique copies an existing file to make the backup copy, then updates the origial file. In an attempt to keep operations atomic, the original file is opened as the first operation and is not closed until all operations are complete. In an attempt to avoid data loss, the original file is not modified until the backup file is closed.
Alternative technique copies an existing file to make the backup copy, then updates the origial file. In an attempt to keep operations atomic, the original file is opened as the first operation and is not closed until all operations are complete. In an attempt to avoid data loss, the original file is not modified until the backup file is closed.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 313: Line 313:
// backup complete (as long as err == nil)
// backup complete (as long as err == nil)
return
return
}</lang>
}</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|7+}}
{{works with|Java|7+}}
<lang java5>import java.io.File;
<syntaxhighlight lang="java5">import java.io.File;
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PrintWriter;
Line 351: Line 351:
}
}
}
}
}</lang>
}</syntaxhighlight>


Contents of 'original.txt' ''before'' the program is run and of 'original.txt.backup' ''after'' it is run:
Contents of 'original.txt' ''before'' the program is run and of 'original.txt.backup' ''after'' it is run:
Line 368: Line 368:


{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.io.File;
<syntaxhighlight lang="java5">import java.io.File;
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.PrintWriter;
Line 397: Line 397:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 405: Line 405:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>targetfile = "pycon-china"
<syntaxhighlight lang="julia">targetfile = "pycon-china"
mv(realpath(targetfile), realpath(targetfile) * ".bak")
mv(realpath(targetfile), realpath(targetfile) * ".bak")
# "a+" for permissions of reading, writing, creating
# "a+" for permissions of reading, writing, creating
open(targetfile, "w+") do io
open(targetfile, "w+") do io
println(io, "this task was solved during a talk about rosettacode at the PyCon China in 2011")
println(io, "this task was solved during a talk about rosettacode at the PyCon China in 2011")
end</lang>
end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.51
<syntaxhighlight lang="scala">// version 1.1.51


import java.io.File
import java.io.File
Line 433: Line 433:
fun main(args: Array<String>) {
fun main(args: Array<String>) {
saveWithBackup("original.txt", "fourth", "fifth", "sixth")
saveWithBackup("original.txt", "fourth", "fifth", "sixth")
}</lang>
}</syntaxhighlight>


Contents of 'original.txt' ''before'' the program is run and of 'original.txt.backup' ''after'' it is run:
Contents of 'original.txt' ''before'' the program is run and of 'original.txt.backup' ''after'' it is run:
Line 450: Line 450:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(file2use = 'input.txt')
<syntaxhighlight lang="lasso">local(file2use = 'input.txt')


// create file
// create file
Line 469: Line 469:
// create new file with new contents
// create new file with new contents
local(nf = file(#file2use))
local(nf = file(#file2use))
#nf->doWithClose => { #nf->writeBytes(#contents_of_f->asBytes) }</lang>
#nf->doWithClose => { #nf->writeBytes(#contents_of_f->asBytes) }</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==
Line 477: Line 477:
=={{header|Nim}}==
=={{header|Nim}}==
In case the backup cannot be done, an exception is raised.
In case the backup cannot be done, an exception is raised.
<lang Nim>import os, strutils
<syntaxhighlight lang="nim">import os, strutils


const
const
Line 525: Line 525:
# Cleanup.
# Cleanup.
setCurrentDir(oldDir)
setCurrentDir(oldDir)
removeDir(Dir)</lang>
removeDir(Dir)</syntaxhighlight>


{{out}}
{{out}}
Line 541: Line 541:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;


Line 580: Line 580:


# back up this program
# back up this program
backup($0,3,'.bk');</lang>
backup($0,3,'.bk');</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Go}}
{{trans|Go}}
<lang Phix>targetfile = get_proper_path("test.txt")
<syntaxhighlight lang="phix">targetfile = get_proper_path("test.txt")
if not rename_file(targetfile, targetfile&".bak", overwrite:=true) then
if not rename_file(targetfile, targetfile&".bak", overwrite:=true) then
puts(1,"warning: could not rename file\n")
puts(1,"warning: could not rename file\n")
Line 594: Line 594:
puts(fn,"this task was translated from the Python entry\n")
puts(fn,"this task was translated from the Python entry\n")
close(fn)
close(fn)
end if</lang>
end if</syntaxhighlight>
Before basing anything on the above code, though, I would recommend you take a look at <br>
Before basing anything on the above code, though, I would recommend you take a look at <br>
function saveFile in demo\edix\edix.exw, which does this sort of thing for real: <br>
function saveFile in demo\edix\edix.exw, which does this sort of thing for real: <br>
Line 601: Line 601:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp makes use of external commands as much as possible (at least for not time-critical operations), to avoid duplicated functionality.
PicoLisp makes use of external commands as much as possible (at least for not time-critical operations), to avoid duplicated functionality.
<lang PicoLisp>(let Path (in '(realpath "foo") (line T))
<syntaxhighlight lang="picolisp">(let Path (in '(realpath "foo") (line T))
(call 'mv Path (pack Path ".backup"))
(call 'mv Path (pack Path ".backup"))
(out Path
(out Path
(prinl "This is the new file") ) )</lang>
(prinl "This is the new file") ) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>string targetfile = "pycon-china";
<syntaxhighlight lang="pike">string targetfile = "pycon-china";
targetfile = System.resolvepath(targetfile);
targetfile = System.resolvepath(targetfile);
mv(targetfile, targetfile+"~");
mv(targetfile, targetfile+"~");
Stdio.write_file(targetfile, "this task was solved at the pycon china 2011");</lang>
Stdio.write_file(targetfile, "this task was solved at the pycon china 2011");</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Using [https://docs.python.org/library/os.html os library]
Using [https://docs.python.org/library/os.html os library]
<syntaxhighlight lang="python">
<lang Python>
import os
import os
targetfile = "pycon-china"
targetfile = "pycon-china"
Line 621: Line 621:
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
f.close()
</syntaxhighlight>
</lang>
Or using a newer [https://docs.python.org/library/pathlib.html pathlib library] (Python >= 3.4):
Or using a newer [https://docs.python.org/library/pathlib.html pathlib library] (Python >= 3.4):
<syntaxhighlight lang="python">
<lang Python>
from pathlib import Path
from pathlib import Path


Line 630: Line 630:
with filepath.open('w') as file:
with filepath.open('w') as file:
file.write("New content")
file.write("New content")
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 636: Line 636:
This version keeps unlimited backups, with <tt>*.bak</tt> being the freshest one, <tt>*.bak1</tt> is an older backup, etc. So each backup moves all existing names up.
This version keeps unlimited backups, with <tt>*.bak</tt> being the freshest one, <tt>*.bak1</tt> is an older backup, etc. So each backup moves all existing names up.


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 654: Line 654:


(revise "fff")
(revise "fff")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 660: Line 660:
{{works with|Rakudo|2017.10}}
{{works with|Rakudo|2017.10}}


<lang perl6># Back up the given path/filename with a default extension .bk(n)
<syntaxhighlight lang="raku" line># Back up the given path/filename with a default extension .bk(n)
# where n is in the range 1 - $limit (default 3).
# where n is in the range 1 - $limit (default 3).
# Prints 'File not found' to STDERR if the file does not exist.
# Prints 'File not found' to STDERR if the file does not exist.
Line 694: Line 694:
# Optionally, specify limit, back-up extension pattern and whether to follow symlinks.
# Optionally, specify limit, back-up extension pattern and whether to follow symlinks.
# Optional parameters can be in any order, in any combination.
# Optional parameters can be in any order, in any combination.
backup 'myfile', :follow-symlinks, :limit(2), :ext('bak');</lang>
backup 'myfile', :follow-symlinks, :limit(2), :ext('bak');</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
This REXX version executes under DOS or DOS under Windows.
This REXX version executes under DOS or DOS under Windows.
<lang rexx>/*REXX program creates a backup file (for a given file), then overwrites the old file.*/
<syntaxhighlight lang="rexx">/*REXX program creates a backup file (for a given file), then overwrites the old file.*/
parse arg oFID . /*get a required argument from the C.L.*/
parse arg oFID . /*get a required argument from the C.L.*/
if oFID=='' then do /*No argument? Then issue an err msg.*/
if oFID=='' then do /*No argument? Then issue an err msg.*/
Line 710: Line 710:
'RENAME' oFID tFID /*rename the original file to backup. */
'RENAME' oFID tFID /*rename the original file to backup. */
call lineout oFID, '═══This is line 1.' /*write one line to the original file. */
call lineout oFID, '═══This is line 1.' /*write one line to the original file. */
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
The contents of the original file (before execution): &nbsp; '''A.FILE''':
The contents of the original file (before execution): &nbsp; '''A.FILE''':
<pre>
<pre>
Line 735: Line 735:
=={{header|Ruby}}==
=={{header|Ruby}}==
This version does not overwrite the backup file if it exists.
This version does not overwrite the backup file if it exists.
<lang ruby>def backup_and_open(filename)
<syntaxhighlight lang="ruby">def backup_and_open(filename)
filename = File.realpath(filename)
filename = File.realpath(filename)
bkup = filename + ".backup"
bkup = filename + ".backup"
Line 753: Line 753:
end
end


1.upto(12) {|i| backup_and_open(ARGV[0]) {|fh| fh.puts "backup #{i}"}}</lang>
1.upto(12) {|i| backup_and_open(ARGV[0]) {|fh| fh.puts "backup #{i}"}}</syntaxhighlight>


Example:
Example:
Line 791: Line 791:
=={{header|Scala}}==
=={{header|Scala}}==
===Java Interoperability===
===Java Interoperability===
<lang Scala>import java.io.{File, PrintWriter}
<syntaxhighlight lang="scala">import java.io.{File, PrintWriter}
import java.nio.file.{Files, Paths, StandardCopyOption}
import java.nio.file.{Files, Paths, StandardCopyOption}


Line 813: Line 813:
saveWithBackup("original.txt", "fourth", "fifth", "sixth")
saveWithBackup("original.txt", "fourth", "fifth", "sixth")


}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


proc backupopen {filename mode} {
proc backupopen {filename mode} {
Line 837: Line 837:
}
}
return [open $filename $mode]
return [open $filename $mode]
}</lang>
}</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub backup(filename As String)
<syntaxhighlight lang="vb">Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
If Len(Dir(filename)) > 0 Then
On Error Resume Next
On Error Resume Next
Line 857: Line 857:
Public Sub main()
Public Sub main()
backup "D:\test.txt"
backup "D:\test.txt"
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-ioutil}}
{{libheader|Wren-ioutil}}
<lang ecmascript>import "/ioutil" for File, FileUtil
<syntaxhighlight lang="ecmascript">import "/ioutil" for File, FileUtil


var saveWithBackup = Fn.new { |filePath, lines|
var saveWithBackup = Fn.new { |filePath, lines|
Line 879: Line 879:
System.print(File.read("original.txt"))
System.print(File.read("original.txt"))
System.print("Contents of original.txt.backup:")
System.print("Contents of original.txt.backup:")
System.print(File.read("original.txt.backup"))</lang>
System.print(File.read("original.txt.backup"))</syntaxhighlight>


{{out}}
{{out}}