File input/output: Difference between revisions
(Added BBC BASIC) |
|||
(245 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task|File |
{{task|File handling}} {{selection|Short Circuit|Console Program Basics}} [[Category:Simple]] |
||
;Task: |
|||
In this task, the job is to create a file called "output.txt", and place in it the contents of the file "input.txt". |
|||
Create a file called "output.txt", and place in it the contents of the file "input.txt", ''via an intermediate variable''. |
|||
In other words, your program will demonstrate: |
|||
::# how to read from a file into a variable |
|||
::# how to write a variable's contents into a file |
|||
<br> |
|||
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that. |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">V file_contents = File(‘input.txt’).read() |
|||
File(‘output.txt’, ‘w’).write(file_contents)</syntaxhighlight> |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
|||
<syntaxhighlight lang="aarch64 assembly"> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program readwrtFile64.s */ |
|||
/*******************************************/ |
|||
/* Constantes file */ |
|||
/*******************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
.equ TAILLEBUF, 1000 |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessErreur: .asciz "Error open input file.\n" |
|||
szMessErreur4: .asciz "Error open output file.\n" |
|||
szMessErreur1: .asciz "Error close file.\n" |
|||
szMessErreur2: .asciz "Error read file.\n" |
|||
szMessErreur3: .asciz "Error write output file.\n" |
|||
/*************************************************/ |
|||
szMessCodeErr: .asciz "Error code décimal : @ \n" |
|||
szNameFileInput: .asciz "input.txt" |
|||
szNameFileOutput: .asciz "output.txt" |
|||
/*******************************************/ |
|||
/* UnInitialized data */ |
|||
/*******************************************/ |
|||
.bss |
|||
sBuffer: .skip TAILLEBUF |
|||
sZoneConv: .skip 24 |
|||
/**********************************************/ |
|||
/* -- Code section */ |
|||
/**********************************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
mov x0,AT_FDCWD |
|||
ldr x1,qAdrszNameFileInput // file name |
|||
mov x2,#O_RDWR // flags |
|||
mov x3,#0 // mode |
|||
mov x8,#OPEN // call system OPEN |
|||
svc #0 |
|||
cmp x0,0 // open error ? |
|||
ble erreur |
|||
mov x19,x0 // save File Descriptor |
|||
ldr x1,qAdrsBuffer // buffer address |
|||
mov x2,TAILLEBUF // buffer size |
|||
mov x8,READ // call system READ |
|||
svc 0 |
|||
cmp x0,0 // read error ? |
|||
ble erreur2 |
|||
mov x20,x0 // length read characters |
|||
// close imput file |
|||
mov x0,x19 // Fd |
|||
mov x8,CLOSE // call system CLOSE |
|||
svc 0 |
|||
cmp x0,0 // close error ? |
|||
blt erreur1 |
|||
// create output file |
|||
mov x0,AT_FDCWD |
|||
ldr x1,qAdrszNameFileOutput // file name |
|||
mov x2,O_CREAT|O_RDWR // flags |
|||
ldr x3,qFicMask1 // Mode |
|||
mov x8,OPEN // call system open file |
|||
svc 0 |
|||
cmp x0,#0 // create error ? |
|||
ble erreur4 |
|||
mov x19,x0 // file descriptor |
|||
ldr x1,qAdrsBuffer |
|||
mov x2,x20 // length to write |
|||
mov x8, #WRITE // select system call 'write' |
|||
svc #0 // perform the system call |
|||
cmp x0,#0 // error write ? |
|||
blt erreur3 |
|||
// close output file |
|||
mov x0,x19 // Fd fichier |
|||
mov x8, #CLOSE // call system CLOSE |
|||
svc #0 |
|||
cmp x0,#0 // error close ? |
|||
blt erreur1 |
|||
mov x0,#0 // return code OK |
|||
b 100f |
|||
erreur: |
|||
ldr x1,qAdrszMessErreur |
|||
bl displayError |
|||
mov x0,#1 // error return code |
|||
b 100f |
|||
erreur1: |
|||
ldr x1,qAdrszMessErreur1 |
|||
bl displayError |
|||
mov x0,#1 // error return code |
|||
b 100f |
|||
erreur2: |
|||
ldr x1,qAdrszMessErreur2 |
|||
bl displayError |
|||
mov x0,#1 // error return code |
|||
b 100f |
|||
erreur3: |
|||
ldr x1,qAdrszMessErreur3 |
|||
bl displayError |
|||
mov x0,#1 // error return code |
|||
b 100f |
|||
erreur4: |
|||
ldr x1,qAdrszMessErreur4 |
|||
bl displayError |
|||
mov x0,#1 // error return code |
|||
b 100f |
|||
100: // end program |
|||
mov x8,EXIT |
|||
svc 0 |
|||
qAdrszNameFileInput: .quad szNameFileInput |
|||
qAdrszNameFileOutput: .quad szNameFileOutput |
|||
qAdrszMessErreur: .quad szMessErreur |
|||
qAdrszMessErreur1: .quad szMessErreur1 |
|||
qAdrszMessErreur2: .quad szMessErreur2 |
|||
qAdrszMessErreur3: .quad szMessErreur3 |
|||
qAdrszMessErreur4: .quad szMessErreur4 |
|||
qAdrsBuffer: .quad sBuffer |
|||
qFicMask1: .quad 0644 |
|||
/******************************************************************/ |
|||
/* display error message */ |
|||
/******************************************************************/ |
|||
/* x0 contains error code */ |
|||
/* x1 contains address error message */ |
|||
displayError: |
|||
stp x2,lr,[sp,-16]! // save registers |
|||
mov x2,x0 // save error code |
|||
mov x0,x1 // display message error |
|||
bl affichageMess |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv // conversion error code |
|||
bl conversion10S // decimal conversion |
|||
ldr x0,qAdrszMessCodeErr |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at @ character |
|||
bl affichageMess // display message final |
|||
ldp x2,lr,[sp],16 // restaur 2 registers |
|||
ret // return to address lr x30 |
|||
qAdrsZoneConv: .quad sZoneConv |
|||
qAdrszMessCodeErr: .quad szMessCodeErr |
|||
/********************************************************/ |
|||
/* File Include fonctions */ |
|||
/********************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly */ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
=={{header|ACL2}}== |
|||
<syntaxhighlight lang="lisp">:set-state-ok t |
|||
(defun read-channel (channel limit state) |
|||
(mv-let (ch state) |
|||
(read-char$ channel state) |
|||
(if (or (null ch) |
|||
(zp limit)) |
|||
(let ((state (close-input-channel channel state))) |
|||
(mv nil state)) |
|||
(mv-let (so-far state) |
|||
(read-channel channel (1- limit) state) |
|||
(mv (cons ch so-far) state))))) |
|||
(defun read-from-file (filename limit state) |
|||
(mv-let (channel state) |
|||
(open-input-channel filename :character state) |
|||
(mv-let (contents state) |
|||
(read-channel channel limit state) |
|||
(mv (coerce contents 'string) state)))) |
|||
(defun write-channel (channel cs state) |
|||
(if (endp cs) |
|||
(close-output-channel channel state) |
|||
(let ((state (write-byte$ (char-code (first cs)) |
|||
channel state))) |
|||
(let ((state (write-channel channel |
|||
(rest cs) |
|||
state))) |
|||
state)))) |
|||
(defun write-to-file (filename str state) |
|||
(mv-let (channel state) |
|||
(open-output-channel filename :byte state) |
|||
(write-channel channel (coerce str 'list) state))) |
|||
(defun copy-file (in out state) |
|||
(mv-let (contents state) |
|||
(read-from-file in (expt 2 40) state) |
|||
(write-to-file out contents state)))</syntaxhighlight> |
|||
=={{header|Action!}}== |
|||
The attached result has been obtained under DOS 2.5. |
|||
{{libheader|Action! Tool Kit}} |
|||
<syntaxhighlight lang="action!">INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit |
|||
PROC Dir(CHAR ARRAY filter) |
|||
BYTE dev=[1] |
|||
CHAR ARRAY line(255) |
|||
Close(dev) |
|||
Open(dev,filter,6) |
|||
DO |
|||
InputSD(dev,line) |
|||
PrintE(line) |
|||
IF line(0)=0 THEN |
|||
EXIT |
|||
FI |
|||
OD |
|||
Close(dev) |
|||
RETURN |
|||
PROC CopyFile(CHAR ARRAY src,dst) |
|||
DEFINE BUF_LEN="1000" |
|||
BYTE in=[1], out=[2] |
|||
BYTE ARRAY buff(BUF_LEN) |
|||
CARD len |
|||
Close(in) |
|||
Close(out) |
|||
Open(in,src,4) |
|||
Open(out,dst,8) |
|||
DO |
|||
len=Bget(in,buff,BUF_LEN) |
|||
IF len>0 THEN |
|||
Bput(out,buff,len) |
|||
FI |
|||
UNTIL len#BUF_LEN |
|||
OD |
|||
Close(in) |
|||
Close(out) |
|||
RETURN |
|||
PROC Main() |
|||
CHAR ARRAY filter="D:*.*", |
|||
src="D:INPUT.TXT", dst="D:OUTPUT.TXT" |
|||
Put(125) PutE() ;clear screen |
|||
PrintF("Dir ""%S""%E",filter) |
|||
Dir(filter) |
|||
PrintF("Copy ""%S"" to ""%S""%E%E",src,dst) |
|||
CopyFile(src,dst) |
|||
PrintF("Dir ""%S""%E",filter) |
|||
Dir(filter) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/File_input_output.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
Dir "D:*.*" |
|||
DOS SYS 037 |
|||
DUP SYS 042 |
|||
INPUT TXT 011 |
|||
617 FREE SECTORS |
|||
Copy "D:INPUT.TXT" to "D:OUTPUT.TXT" |
|||
Dir "D:*.*" |
|||
DOS SYS 037 |
|||
DUP SYS 042 |
|||
INPUT TXT 011 |
|||
OUTPUT TXT 011 |
|||
606 FREE SECTORS |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
If the file line size exceeds the size of the input string the output file will contain extra new-line characters. |
|||
===Line by line=== |
|||
<lang ada>with Ada.Text_IO; use Ada.Text_IO; |
|||
procedure File_IO is |
|||
Assuming everything is fine and no error handling is required, this solution is sufficient: |
|||
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
|||
procedure Read_And_Write_File_Line_By_Line is |
|||
Input, Output : File_Type; |
Input, Output : File_Type; |
||
Line : String (1 .. 10_000); |
|||
Last : Natural; |
|||
begin |
begin |
||
Open (File => Input, |
|||
Create (Output, Out_File, "output.txt"); |
|||
Mode => In_File, |
|||
Name => "input.txt"); |
|||
while not End_Of_File (Input) loop |
|||
Create (File => Output, |
|||
Get_Line (Input, Line, Last); |
|||
Mode => Out_File, |
|||
Name => "output.txt"); |
|||
loop |
|||
declare |
|||
Line : String := Get_Line (Input); |
|||
begin |
|||
-- You can process the contents of Line here. |
|||
Put_Line (Output, Line); |
|||
end; |
|||
end loop; |
end loop; |
||
Close (Input); |
Close (Input); |
||
Close (Output); |
Close (Output); |
||
exception |
|||
end File_IO;</lang> |
|||
when End_Error => |
|||
Note that it is possible to use a version of Get_Line that returns the read line as one string of unspecified length: |
|||
if Is_Open(Input) then |
|||
Close (Input); |
|||
end |
end if; |
||
if Is_Open(Output) then |
|||
But it is not recommended, because it would make program vulnerable to storage error problems. |
|||
Close (Output); |
|||
end if; |
|||
end Read_And_Write_File_Line_By_Line;</syntaxhighlight> |
|||
Expanded with proper error handling and reporting it reads: |
|||
The following example reads and writes each file one character at a time. There is no new-line issue. |
|||
<lang ada>with Ada.Sequential_Io; |
|||
<syntaxhighlight lang="ada">with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO; |
|||
procedure |
procedure Read_And_Write_File_Line_By_Line is |
||
Read_From : constant String := "input.txt"; |
|||
package Char_Io is new Ada.Sequential_Io(Character); |
|||
Write_To : constant String := "output.txt"; |
|||
use Char_Io; |
|||
Infile, Outfile : File_Type; |
|||
Input, Output : File_Type; |
|||
begin |
begin |
||
begin |
|||
Create(File => Outfile, Mode => Out_File, Name => "output.txt"); |
|||
Open(File => |
Open (File => Input, |
||
Mode => In_File, |
|||
while not End_Of_File(Infile) loop |
|||
Name => Read_From); |
|||
exception |
|||
Write(File => Outfile, Item => Value); |
|||
when others => |
|||
Put_Line (Standard_Error, |
|||
"Can not open the file '" & Read_From & "'. Does it exist?"); |
|||
Set_Exit_Status (Failure); |
|||
return; |
|||
end; |
|||
begin |
|||
Create (File => Output, |
|||
Mode => Out_File, |
|||
Name => Write_To); |
|||
exception |
|||
when others => |
|||
Put_Line (Standard_Error, |
|||
"Can not create a file named '" & Write_To & "'."); |
|||
Set_Exit_Status (Failure); |
|||
return; |
|||
end; |
|||
loop |
|||
declare |
|||
Line : String := Get_Line (Input); |
|||
begin |
|||
-- You can process the contents of Line here. |
|||
Put_Line (Output, Line); |
|||
end; |
|||
end loop; |
end loop; |
||
Close( |
Close (Input); |
||
Close( |
Close (Output); |
||
exception |
|||
end File_IO;</lang> |
|||
when End_Error => |
|||
The following solution uses stream I/O. Any file of Ada.Text_IO can be used to obtain a corresponding stream. Reading and writing streams is more efficient than reading text files directly, because it skips formatting. Note also how End_Error exception is used to avoid End_Of_File. End_Of_File is depreciated as it requires file look-ahead, and thus is much less efficient. |
|||
if Is_Open(Input) then |
|||
<lang ada>with Ada.Text_IO; use Ada.Text_IO; |
|||
Close (Input); |
|||
end if; |
|||
if Is_Open(Output) then |
|||
Close (Output); |
|||
end if; |
|||
end Read_And_Write_File_Line_By_Line;</syntaxhighlight> |
|||
===Character by character=== |
|||
The following example reads and writes each file one character at a time. (You should of course add error reporting as in the example above.) |
|||
<syntaxhighlight lang="ada">with Ada.Sequential_IO; |
|||
procedure Read_And_Write_File_Character_By_Character is |
|||
package Char_IO is new Ada.Sequential_IO (Character); |
|||
use Char_IO; |
|||
Input, Output : File_Type; |
|||
Buffer : Character; |
|||
begin |
|||
Open (File => Input, Mode => In_File, Name => "input.txt"); |
|||
Create (File => Output, Mode => Out_File, Name => "output.txt"); |
|||
loop |
|||
Read (File => Input, Item => Buffer); |
|||
Write (File => Output, Item => Buffer); |
|||
end loop; |
|||
Close (Input); |
|||
Close (Output); |
|||
exception |
|||
when End_Error => |
|||
if Is_Open(Input) then |
|||
Close (Input); |
|||
end if; |
|||
if Is_Open(Output) then |
|||
Close (Output); |
|||
end if; |
|||
end Read_And_Write_File_Character_By_Character;</syntaxhighlight> |
|||
===Using Ada.Text_IO.Text_Streams=== |
|||
The following solution uses stream I/O. Any file of Ada.Text_IO can be used to obtain a corresponding stream. Reading and writing streams is more efficient than reading text files directly, because it skips formatting. |
|||
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
|||
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams; |
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams; |
||
procedure |
procedure Using_Text_Streams is |
||
Input, Output : File_Type; |
|||
Buffer : Character; |
|||
begin |
begin |
||
Open (File => Input, Mode => In_File, Name => "input.txt"); |
|||
Create (File => Output, Mode => Out_File, Name => "output.txt"); |
|||
loop |
loop |
||
Buffer := Character'Input (Stream (Input)); |
|||
Character'Write (Stream (Output), Buffer); |
|||
end loop; |
end loop; |
||
Close (Input); |
|||
Close (Output); |
|||
exception |
exception |
||
when End_Error => |
when End_Error => |
||
if Is_Open(Input) then |
|||
Close ( |
Close (Input); |
||
end if; |
|||
end File_IO;</lang> |
|||
if Is_Open(Output) then |
|||
Close (Output); |
|||
end if; |
|||
end Using_Text_Streams;</syntaxhighlight> |
|||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">file i, o; |
|||
text s; |
|||
i.open("input.txt", OPEN_READONLY, 0); |
|||
o.open("output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, |
|||
0644); |
|||
while (i.line(s) ^ -1) { |
|||
o.text(s); |
|||
o.byte('\n'); |
|||
}</syntaxhighlight> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
||
Line 67: | Line 460: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
||
< |
<syntaxhighlight lang="algol68">PROC copy file v1 = (STRING in name, out name)VOID: ( |
||
# note: algol68toc-1.18 - can compile, but not run v1 # |
# note: algol68toc-1.18 - can compile, but not run v1 # |
||
INT errno; |
INT errno; |
||
Line 112: | Line 505: | ||
test:( |
test:( |
||
copy file v2("input.txt","output.txt") |
copy file v2("input.txt","output.txt") |
||
)</ |
)</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">on copyFile from src into dst |
||
set filedata to read file src |
set filedata to read file src |
||
set outfile to open for access dst with write permission |
set outfile to open for access dst with write permission |
||
Line 122: | Line 515: | ||
end copyFile |
end copyFile |
||
copyFile from ":input.txt" into ":output.txt"</ |
copyFile from ":input.txt" into ":output.txt"</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
|||
{{works with|as|Raspberry Pi}} |
|||
<syntaxhighlight lang="arm assembly"> |
|||
/* ARM assembly Raspberry PI */ |
|||
/* program readwrtfile.s */ |
|||
/*********************************************/ |
|||
/*constantes */ |
|||
/********************************************/ |
|||
.equ STDOUT, 1 @ Linux output console |
|||
.equ EXIT, 1 @ Linux syscall |
|||
.equ READ, 3 |
|||
.equ WRITE, 4 |
|||
.equ OPEN, 5 |
|||
.equ CLOSE, 6 |
|||
.equ CREATE, 8 |
|||
/* file */ |
|||
.equ O_RDWR, 0x0002 @ open for reading and writing |
|||
.equ TAILLEBUF, 1000 |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessErreur: .asciz "Erreur ouverture fichier input.\n" |
|||
szMessErreur4: .asciz "Erreur création fichier output.\n" |
|||
szMessErreur1: .asciz "Erreur fermeture fichier.\n" |
|||
szMessErreur2: .asciz "Erreur lecture fichier.\n" |
|||
szMessErreur3: .asciz "Erreur d'écriture dans fichier de sortie.\n" |
|||
szRetourligne: .asciz "\n" |
|||
szMessErr: .ascii "Error code : " |
|||
sDeci: .space 15,' ' |
|||
.asciz "\n" |
|||
szNameFileInput: .asciz "input.txt" |
|||
szNameFileOutput: .asciz "output.txt" |
|||
/*******************************************/ |
|||
/* DONNEES NON INITIALISEES */ |
|||
/*******************************************/ |
|||
.bss |
|||
sBuffer: .skip TAILLEBUF |
|||
/**********************************************/ |
|||
/* -- Code section */ |
|||
/**********************************************/ |
|||
.text |
|||
.global main |
|||
main: |
|||
push {fp,lr} /* save registers */ |
|||
ldr r0,iAdrszNameFileInput @ file name |
|||
mov r1,#O_RDWR @ flags |
|||
mov r2,#0 @ mode |
|||
mov r7,#OPEN @ call system OPEN |
|||
swi #0 |
|||
cmp r0,#0 @ open error ? |
|||
ble erreur |
|||
mov r8,r0 @ save File Descriptor |
|||
ldr r1,iAdrsBuffer @ buffer address |
|||
mov r2,#TAILLEBUF @ buffer size |
|||
mov r7, #READ @ call system READ |
|||
swi 0 |
|||
cmp r0,#0 @ read error ? |
|||
ble erreur2 |
|||
mov r2,r0 @ length read characters |
|||
/* close imput file */ |
|||
mov r0,r8 @ Fd |
|||
mov r7, #CLOSE @ call system CLOSE |
|||
swi 0 |
|||
cmp r0,#0 @ close error ? |
|||
blt erreur1 |
|||
@ create output file |
|||
ldr r0,iAdrszNameFileOutput @ file name |
|||
ldr r1,iFicMask1 @ flags |
|||
mov r7, #CREATE @ call system create file |
|||
swi 0 |
|||
cmp r0,#0 @ create error ? |
|||
ble erreur4 |
|||
mov r0,r8 @ file descriptor |
|||
ldr r1,iAdrsBuffer |
|||
@ et r2 contains the length to write |
|||
mov r7, #WRITE @ select system call 'write' |
|||
swi #0 @ perform the system call |
|||
cmp r0,#0 @ error write ? |
|||
blt erreur3 |
|||
@ close output file |
|||
mov r0,r8 @ Fd fichier |
|||
mov r7, #CLOSE @ call system CLOSE |
|||
swi #0 |
|||
cmp r0,#0 @ error close ? |
|||
blt erreur1 |
|||
mov r0,#0 @ return code OK |
|||
b 100f |
|||
erreur: |
|||
ldr r1,iAdrszMessErreur |
|||
bl afficheerreur |
|||
mov r0,#1 @ error return code |
|||
b 100f |
|||
erreur1: |
|||
ldr r1,iAdrszMessErreur1 |
|||
bl afficheerreur |
|||
mov r0,#1 @ error return code |
|||
b 100f |
|||
erreur2: |
|||
ldr r1,iAdrszMessErreur2 |
|||
bl afficheerreur |
|||
mov r0,#1 @ error return code |
|||
b 100f |
|||
erreur3: |
|||
ldr r1,iAdrszMessErreur3 |
|||
bl afficheerreur |
|||
mov r0,#1 @ error return code |
|||
b 100f |
|||
erreur4: |
|||
ldr r1,iAdrszMessErreur4 |
|||
bl afficheerreur |
|||
mov r0,#1 @ error return code |
|||
b 100f |
|||
100: @ end program |
|||
pop {fp,lr} /* restaur des 2 registres */ |
|||
mov r7, #EXIT /* appel fonction systeme pour terminer */ |
|||
swi 0 |
|||
iAdrszNameFileInput: .int szNameFileInput |
|||
iAdrszNameFileOutput: .int szNameFileOutput |
|||
iAdrszMessErreur: .int szMessErreur |
|||
iAdrszMessErreur1: .int szMessErreur1 |
|||
iAdrszMessErreur2: .int szMessErreur2 |
|||
iAdrszMessErreur3: .int szMessErreur3 |
|||
iAdrszMessErreur4: .int szMessErreur4 |
|||
iAdrsBuffer: .int sBuffer |
|||
iFicMask1: .octa 0644 |
|||
/******************************************************************/ |
|||
/* display text with size calculation */ |
|||
/******************************************************************/ |
|||
/* r0 contains the address of the message */ |
|||
affichageMess: |
|||
push {r0,r1,r2,r7,lr} /* save registres */ |
|||
mov r2,#0 /* counter length */ |
|||
1: /* loop length calculation */ |
|||
ldrb r1,[r0,r2] /* read octet start position + index */ |
|||
cmp r1,#0 /* if 0 its over */ |
|||
addne r2,r2,#1 /* else add 1 in the length */ |
|||
bne 1b /* and loop */ |
|||
/* so here r2 contains the length of the message */ |
|||
mov r1,r0 /* address message in r1 */ |
|||
mov r0,#STDOUT /* code to write to the standard output Linux */ |
|||
mov r7, #WRITE /* code call system "write" */ |
|||
swi #0 /* call systeme */ |
|||
pop {r0,r1,r2,r7,lr} /* restaur des 2 registres */ |
|||
bx lr /* return */ |
|||
/***************************************************/ |
|||
/* display error message */ |
|||
/***************************************************/ |
|||
/* r0 contains error code r1 address error message */ |
|||
afficheerreur: |
|||
push {r1-r2,lr} @ save registers |
|||
mov r2,r0 @ save error code |
|||
mov r0,r1 @ address error message |
|||
bl affichageMess @ display error message |
|||
mov r0,r2 @ error code |
|||
ldr r1,iAdrsDeci @ result address |
|||
bl conversion10S |
|||
ldr r0,iAdrszMessErr @ display error code |
|||
bl affichageMess |
|||
pop {r1-r2,lr} @ restaur registers |
|||
bx lr @ return function |
|||
iAdrszMessErr: .int szMessErr |
|||
iAdrsDeci: .int sDeci |
|||
/***************************************************/ |
|||
/* Converting a register to a signed decimal */ |
|||
/***************************************************/ |
|||
/* r0 contains value and r1 area address */ |
|||
conversion10S: |
|||
push {r0-r4,lr} @ save registers |
|||
mov r2,r1 /* debut zone stockage */ |
|||
mov r3,#'+' /* par defaut le signe est + */ |
|||
cmp r0,#0 @ negative number ? |
|||
movlt r3,#'-' @ yes |
|||
mvnlt r0,r0 @ number inversion |
|||
addlt r0,#1 |
|||
mov r4,#10 @ length area |
|||
1: @ start loop |
|||
bl divisionPar10R |
|||
add r1,#48 @ digit |
|||
strb r1,[r2,r4] @ store digit on area |
|||
sub r4,r4,#1 @ previous position |
|||
cmp r0,#0 @ stop if quotient = 0 |
|||
bne 1b |
|||
strb r3,[r2,r4] @ store signe |
|||
subs r4,r4,#1 @ previous position |
|||
blt 100f @ if r4 < 0 -> end |
|||
mov r1,#' ' @ space |
|||
2: |
|||
strb r1,[r2,r4] @store byte space |
|||
subs r4,r4,#1 @ previous position |
|||
bge 2b @ loop if r4 > 0 |
|||
100: |
|||
pop {r0-r4,lr} @ restaur registers |
|||
bx lr |
|||
/***************************************************/ |
|||
/* division for 10 fast unsigned */ |
|||
/***************************************************/ |
|||
@ r0 contient le dividende |
|||
@ r0 retourne le quotient |
|||
@ r1 retourne le reste |
|||
divisionPar10R: |
|||
push {r2,lr} @ save registers |
|||
sub r1, r0, #10 @ calcul de r0 - 10 |
|||
sub r0, r0, r0, lsr #2 @ calcul de r0 - (r0 /4) |
|||
add r0, r0, r0, lsr #4 @ calcul de (r0-(r0/4))+ ((r0-(r0/4))/16 |
|||
add r0, r0, r0, lsr #8 @ etc ... |
|||
add r0, r0, r0, lsr #16 |
|||
mov r0, r0, lsr #3 |
|||
add r2, r0, r0, asl #2 |
|||
subs r1, r1, r2, asl #1 @ calcul (N-10) - (N/10)*10 |
|||
addpl r0, r0, #1 @ regul quotient |
|||
addmi r1, r1, #10 @ regul reste |
|||
pop {r2,lr} |
|||
bx lr |
|||
</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">source: read "input.txt" |
|||
write "output.txt" source |
|||
print source</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Method 1: the input file can be processed line by line. |
Method 1: the input file can be processed line by line. |
||
< |
<syntaxhighlight lang="autohotkey">Loop, Read, input.txt, output.txt |
||
FileAppend, %A_LoopReadLine%`n</ |
FileAppend, %A_LoopReadLine%`n</syntaxhighlight> |
||
Method 2: the input file can be read at once if it is less than 1 GB. |
Method 2: the input file can be read at once if it is less than 1 GB. |
||
< |
<syntaxhighlight lang="autohotkey">FileRead, var, input.txt |
||
FileAppend, %var%, output.txt</ |
FileAppend, %var%, output.txt</syntaxhighlight> |
||
Method 3: the file can be copied without |
Method 3: the file can be copied without I/O. |
||
< |
<syntaxhighlight lang="autohotkey">FileCopy, input.txt, output.txt</syntaxhighlight> |
||
Binary |
Binary I/O is possible with [http://www.autohotkey.com/forum/topic4604.html&highlight=binread this] library from Laszlo. |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 140: | Line 771: | ||
(This does not handle properly binary files) |
(This does not handle properly binary files) |
||
< |
<syntaxhighlight lang="awk">BEGIN { |
||
while ( (getline <"input.txt") > 0 ) { |
while ( (getline <"input.txt") > 0 ) { |
||
print >"output.txt" |
print >"output.txt" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
|||
<syntaxhighlight lang="babel">(main |
|||
{ "input.txt" >>> -- File is now on stack |
|||
foo set -- File is now in 'foo' |
|||
foo "output.txt" <<< })</syntaxhighlight> |
|||
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example, |
|||
I showed how to save it into a symbolic variable (foo) but this step would not be necessary |
|||
for many simple file-processing tasks, such as splitting on newlines or spaces. |
|||
Also note that the >>> (slurp) and <<< (spit) operators only handle "small" files - the limit is |
|||
configurable but the default limit is 100MB. If you want to open very large files or if you need |
|||
to perform a lot of interactive file I/O, Babel provides operators that wrap the C standard library |
|||
fopen()/fclose() functions. |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|Applesoft BASIC}}=== |
|||
This is only meant to copy a sequential text file. It is very unlikely that this works copying a random access text file. |
|||
<syntaxhighlight lang="applesoftbasic">100 I$ = "INPUT.TXT" |
|||
110 O$ = "OUTPUT.TXT" |
|||
120 M$ = CHR$(13) |
|||
130 D$ = CHR$(4) |
|||
140 PRINT D$"VERIFY"I$ |
|||
150 PRINT D$"OPEN"O$ |
|||
160 PRINT D$"DELETE"O$ |
|||
170 PRINT D$"OPEN"O$ |
|||
180 PRINT D$"OPEN"I$ |
|||
190 PRINT D$"READ"I$ |
|||
200 ONERR GOTO 280 |
|||
210 GET C$ |
|||
220 POKE 216,0 |
|||
230 PRINT M$D$"WRITE"O$",B"B |
|||
240 B = B + 1 |
|||
250 P = 2 - (C$ <> M$) |
|||
260 PRINT MID$(C$, P) |
|||
270 GOTO 190 |
|||
280 POKE 216,0 |
|||
290 EOF = PEEK(222) = 5 |
|||
300 IF NOT EOF THEN RESUME |
|||
310 PRINT M$D$"CLOSE" |
|||
</syntaxhighlight> |
|||
==={{header|BaCon}}=== |
|||
<syntaxhighlight lang="freebasic"> |
|||
text$ = LOAD$("input.txt") |
|||
SAVE text$ TO "output.txt" |
|||
</syntaxhighlight> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="freebasic">open 1, "input.txt" |
|||
open 2, "output.txt" |
|||
while not eof(1) |
|||
linea$ = readline(1) |
|||
write 2, linea$ |
|||
end while |
|||
close 1 |
|||
close 2</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
[[BBC BASIC for Windows]] has a file copy command: |
|||
<syntaxhighlight lang="bbcbasic">*COPY input.txt output.txt</syntaxhighlight> |
|||
Alternatively the copy can be done explicitly: |
|||
<syntaxhighlight lang="bbcbasic">infile% = OPENIN("input.txt") |
|||
outfile% = OPENOUT("output.txt") |
|||
WHILE NOT EOF#infile% |
|||
BPUT #outfile%, BGET#infile% |
|||
ENDWHILE |
|||
CLOSE #infile% |
|||
CLOSE #outfile%</syntaxhighlight> |
|||
==={{header|Commodore BASIC}}=== |
|||
<syntaxhighlight lang="commodorebasic">10 print chr$(14) : rem switch to upper+lower case set |
|||
20 print "read seq file input.txt and write to seq file output.txt" |
|||
30 open 4,8,4,"input.txt,seq,read" |
|||
40 open 8,8,8,"@:output.txt,seq,write" : rem '@'== new file |
|||
50 for i=0 to 1 : rem while i==0 |
|||
60 input#4,a$ |
|||
70 i=64 and st : rem check bit 6=='end of file' |
|||
80 print a$ |
|||
90 print#8,a$ |
|||
100 next : rem end while |
|||
110 close 4 |
|||
120 close 8 |
|||
130 end</syntaxhighlight> |
|||
==={{header|FreeBASIC}}=== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
/' |
|||
input.txt contains: |
|||
The quick brown fox jumps over the lazy dog. |
|||
Empty vessels make most noise. |
|||
Too many chefs spoil the broth. |
|||
A rolling stone gathers no moss. |
|||
'/ |
|||
Open "output.txt" For Output As #1 |
|||
Open "input.txt" For Input As #2 |
|||
Dim line_ As String ' note that line is a keyword |
|||
While Not Eof(2) |
|||
Line Input #2, line_ |
|||
Print #1, line_ |
|||
Wend |
|||
Close #2 |
|||
Close #1</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
output.txt contains: |
|||
The quick brown fox jumps over the lazy dog. |
|||
Empty vessels make most noise. |
|||
Too many chefs spoil the broth. |
|||
A rolling stone gathers no moss. |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
Modified May 2024 |
|||
Prompts the user for an input text file. |
|||
Rich Love |
|||
<syntaxhighlight lang="futurebasic"> |
|||
/* |
|||
Rosetta Code File input/output example |
|||
FutureBasic 7.0.24 |
|||
Rich Love |
|||
5/11/24 |
|||
*/ |
|||
output file "FileInputOutput.app" |
|||
void Local fn doIt |
|||
CFURLRef ParentDirectory // Create a url for the desktop |
|||
ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) |
|||
CFURLRef outputURL // Create a url for output.txt on the desktop |
|||
outputURL = fn URLByAppendingPathComponent( ParentDirectory, @"output.txt" ) |
|||
CFURLRef inputURL = openpanel( 1, @"Open a text file",@"txt") |
|||
if inputURL = NULL then end |
|||
str255 dataLine |
|||
dataLine = "" |
|||
if fn FileManagerContentsAtURL(inputURL) <> NULL |
|||
open "I", 1, inputURL |
|||
open "O", 2, outputURL |
|||
While Not Eof(1) |
|||
Line Input #1, dataLine |
|||
Print #2, dataLine |
|||
Wend |
|||
Close #2 |
|||
Close #1 |
|||
alert 3,,@"File created on Desktop",@"output.txt",@"OK" |
|||
end |
|||
else |
|||
alert 3,,@"File Not Found on Desktop",@"input.txt",@"OK" |
|||
end |
|||
end if |
|||
end fn |
|||
void local fn DoAppEvent( ev as long ) |
|||
select (ev) |
|||
case _appDidFinishLaunching |
|||
fn doIt |
|||
end select |
|||
end fn |
|||
on AppEvent fn DoAppEvent |
|||
handleevents |
|||
</syntaxhighlight> |
|||
==={{header|Gambas}}=== |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim sOutput As String = "Hello " |
|||
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored |
|||
File.Save(User.Home &/ "output.txt", sOutput) |
|||
File.Save(User.Home &/ "input.txt", sOutput & sInput) |
|||
Print "'input.txt' contains - " & sOutput & sInput |
|||
Print "'output.txt' contains - " & sOutput |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
'input.txt' contains - Hello World! |
|||
'output.txt' contains - Hello |
|||
</pre> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 STRING TX$*254 |
|||
110 OPEN #1:"output.txt" |
|||
120 OPEN #2:"input.txt" ACCESS OUTPUT |
|||
130 WHEN EXCEPTION USE IOERROR |
|||
140 DO |
|||
150 LINE INPUT #1:TX$ |
|||
160 PRINT #2:TX$ |
|||
170 LOOP |
|||
180 END WHEN |
|||
190 HANDLER IOERROR |
|||
200 IF EXTYPE<>8001 THEN PRINT EXSTRING$(EXTYPE) |
|||
210 CLOSE #1 |
|||
220 CLOSE #2 |
|||
230 END HANDLER</syntaxhighlight> |
|||
==={{header|Liberty BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
<syntaxhighlight lang="lb">nomainwin |
|||
open "input.txt" for input as #f1 |
|||
qtyBytes = lof( #f1) |
|||
source$ = input$( #f1, qtyBytes) |
|||
close #f1 |
|||
open "output.txt" for output as #f2 |
|||
#f2 source$; |
|||
close #f2 |
|||
end</syntaxhighlight> |
|||
==={{header|PureBasic}}=== |
|||
====Basic file copy==== |
|||
<syntaxhighlight lang="purebasic">CopyFile("input.txt","output.txt")</syntaxhighlight> |
|||
====Line by line==== |
|||
<syntaxhighlight lang="purebasic">in = ReadFile(#PB_Any,"input.txt") |
|||
If in |
|||
out = CreateFile(#PB_Any,"output.txt") |
|||
If out |
|||
Define MyLine$ |
|||
While Not Eof(in) |
|||
MyLine$ = ReadString(in) |
|||
WriteString(out,MyLine$) |
|||
Wend |
|||
CloseFile(out) |
|||
EndIf |
|||
CloseFile(in) |
|||
EndIf</syntaxhighlight> |
|||
====Reading & writing the complete file in one pass==== |
|||
<syntaxhighlight lang="purebasic">If ReadFile(0,"input.txt") |
|||
Define MyLine$, *Buffer, length |
|||
length=FileSize("input.txt") |
|||
*Buffer = AllocateMemory(length) |
|||
If *Buffer |
|||
If OpenFile(1,"output.txt") |
|||
ReadData(0, *Buffer, length) |
|||
WriteData(1, *Buffer, length) |
|||
CloseFile(1) |
|||
EndIf |
|||
FreeMemory(*Buffer) |
|||
EndIf |
|||
CloseFile(0) |
|||
EndIf</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
|||
See [[#QuickBASIC|QuickBASIC]]. |
|||
==={{header|QuickBASIC}}=== |
|||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
{{works with|QBasic}} |
|||
<lang qbasic> OPEN "INPUT.TXT" FOR INPUT AS #1 |
|||
<syntaxhighlight lang="qbasic"> |
|||
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2 |
|||
' File input/output |
|||
DO UNTIL EOF(1) |
|||
OPEN "INPUT.TXT" FOR INPUT AS #1 |
|||
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2 |
|||
PRINT #2, Data$ |
|||
DO UNTIL EOF(1) |
|||
LOOP |
|||
LINE INPUT #1, Data$ |
|||
CLOSE #1 |
|||
PRINT #2, Data$ |
|||
CLOSE #2 |
|||
LOOP |
|||
SYSTEM</lang> |
|||
CLOSE #1 |
|||
CLOSE #2 |
|||
END |
|||
</syntaxhighlight> |
|||
==={{header|RapidQ}}=== |
|||
File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams. |
|||
The first version copies text line by line, as in the ''BASIC'' example. |
|||
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc" |
|||
DIM File1 AS QFileStream |
|||
DIM File2 AS QFileStream |
|||
File1.Open("input.txt", fmOpenRead) |
|||
File2.Open("output.txt", fmCreate) |
|||
WHILE NOT File1.EOF |
|||
data$ = File1.ReadLine |
|||
File2.WriteLine(data$) |
|||
WEND |
|||
File1.Close |
|||
File2.Close</syntaxhighlight> |
|||
When just copying data, the code can be simplified by using the CopyFrom method.<br /> |
|||
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.) |
|||
<syntaxhighlight lang="rapidq">$INCLUDE "rapidq.inc" |
|||
DIM File1 AS QFileStream |
|||
DIM File2 AS QFileStream |
|||
File1.Open("input.txt", fmOpenRead) |
|||
File2.Open("output.txt", fmCreate) |
|||
File2.CopyFrom(File1, 0) |
|||
File1.Close |
|||
File2.Close</syntaxhighlight> |
|||
==={{header|REALbasic}}=== |
|||
<syntaxhighlight lang="vb"> |
|||
Sub WriteToFile(input As FolderItem, output As FolderItem) |
|||
Dim tis As TextInputStream |
|||
Dim tos As TextOutputStream |
|||
tis = tis.Open(input) |
|||
tos = tos.Create(output) |
|||
While Not tis.EOF |
|||
tos.WriteLine(tis.ReadLine) |
|||
Wend |
|||
tis.Close |
|||
tos.Close |
|||
End Sub |
|||
</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in |
|||
fileLen = LOF(#in) 'Length Of File |
|||
fileData$ = input$(#in, fileLen) 'read entire file |
|||
close #in |
|||
open "output.txt" for output as #out |
|||
print #out, fileData$ 'write entire fie |
|||
close #out |
|||
end |
|||
</syntaxhighlight> |
|||
Or directly with no intermediate fileData$ |
|||
{{works with|Just BASIC}} |
|||
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in |
|||
open "output.txt" for output as #out |
|||
fileLen = LOF(#in) 'Length Of File |
|||
print #out, input$(#in, fileLen) 'entire file |
|||
close #in |
|||
close #out |
|||
</syntaxhighlight> |
|||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">OPEN #1: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD |
|||
OPEN #2: NAME "output.txt", CREATE NEWOLD |
|||
ERASE #2 |
|||
DO |
|||
LINE INPUT #1: linea$ |
|||
PRINT #2: linea$ |
|||
LOOP UNTIL END #1 |
|||
CLOSE #1 |
|||
CLOSE #2 |
|||
END</syntaxhighlight> |
|||
==={{header|VBA}}=== |
|||
<syntaxhighlight lang="vb">Option Explicit |
|||
Sub Main() |
|||
Dim s As String, FF As Integer |
|||
'read a file line by line |
|||
FF = FreeFile |
|||
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF |
|||
While Not EOF(FF) |
|||
Line Input #FF, s |
|||
Debug.Print s |
|||
Wend |
|||
Close #FF |
|||
'read a file |
|||
FF = FreeFile |
|||
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF |
|||
s = Input(LOF(1), #FF) |
|||
Close #FF |
|||
Debug.Print s |
|||
'write a file |
|||
FF = FreeFile |
|||
Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF |
|||
Print #FF, s |
|||
Close #FF |
|||
End Sub</syntaxhighlight> |
|||
==={{header|VBScript}}=== |
|||
One liner (-2 for system default encoding) |
|||
<syntaxhighlight lang="vb">CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</syntaxhighlight> |
|||
==={{header|Visual Basic .NET}}=== |
|||
{{works with|Visual Basic .NET|9.0+}} |
|||
====Byte copy==== |
|||
<syntaxhighlight lang="vbnet">My.Computer.FileSystem.WriteAllBytes("output.txt", _ |
|||
My.Computer.FileSystem.ReadAllBytes("input.txt"), False) |
|||
</syntaxhighlight> |
|||
====Text copy==== |
|||
<syntaxhighlight lang="vbnet">Using input = IO.File.OpenText("input.txt"), _ |
|||
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt")) |
|||
output.Write(input.ReadToEnd) |
|||
End Using</syntaxhighlight> |
|||
====Line by line text copy==== |
|||
<syntaxhighlight lang="vbnet">Using input = IO.File.OpenText("input.txt"), _ |
|||
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt")) |
|||
Do Until input.EndOfStream |
|||
output.WriteLine(input.ReadLine) |
|||
Loop |
|||
End Using</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">open "input.txt" for reading as #1 |
|||
open "output.txt" for writing as #2 |
|||
while not eof(1) |
|||
line input #1 linea$ |
|||
print #2 linea$ |
|||
wend |
|||
close #1 |
|||
close #2</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
<lang |
<syntaxhighlight lang="dos">copy input.txt output.txt</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="dos">type input.txt > output.txt</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="dos">for /f "" %L in ('more^<input.txt') do echo %L>>output.txt</syntaxhighlight> |
||
There may be other techniques too. |
There may be other techniques too. |
||
=={{header| |
=={{header|BCPL}}== |
||
<syntaxhighlight lang="bcpl">GET "libhdr" |
|||
<lang bbcbasic> infile% = OPENIN("input.txt") |
|||
outfile% = OPENOUT("output.txt") |
|||
LET start() BE $( |
|||
WHILE NOT EOF#infile% |
|||
BPUT #outfile%, BGET#infile% |
|||
// Attempt to open the named files. |
|||
ENDWHILE |
|||
LET source = findinput("input.txt") |
|||
CLOSE #infile% |
|||
LET destination = findoutput("output.txt") |
|||
CLOSE #outfile%</lang> |
|||
TEST source = 0 THEN |
|||
writes("Unable to open input.txt*N") |
|||
ELSE TEST destination = 0 THEN |
|||
writes("Unable to open output.txt*N") |
|||
ELSE $( |
|||
// The current character, initially unknown. |
|||
LET ch = ? |
|||
// Make the open files the current input and output streams. |
|||
selectinput(source) |
|||
selectoutput(destination) |
|||
// Copy the input to the output character by character until |
|||
// endstreamch is returned to indicate input is exhausted. |
|||
ch := rdch() |
|||
UNTIL ch = endstreamch DO $( |
|||
wrch(ch) |
|||
ch := rdch() |
|||
$) |
|||
// Close the currently selected streams. |
|||
endread() |
|||
endwrite() |
|||
$) |
|||
$)</syntaxhighlight> |
|||
=={{header|Beef}}== |
|||
<syntaxhighlight lang="csharp">using System; |
|||
using System.IO; |
|||
namespace FileIO |
|||
{ |
|||
class Program |
|||
{ |
|||
static void Main() |
|||
{ |
|||
String s = scope .(); |
|||
File.ReadAllText("input.txt", s); |
|||
File.WriteAllText("output.txt", s); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
{{works with|CCBI|2.1}} |
{{works with|CCBI|2.1}} |
||
< |
<syntaxhighlight lang="befunge">0110"txt.tupni"#@i10"txt.tuptuo"#@o@</syntaxhighlight> |
||
This linear program tries to open "input.txt" as text file (or aborts). |
This linear program tries to open "input.txt" as text file (or aborts). |
||
It then writes the content in text mode (i.e. minus trailing spaces) to "output.txt" (or aborts). |
It then writes the content in text mode (i.e. minus trailing spaces) to "output.txt" (or aborts). |
||
=={{header|BQN}}== |
|||
<syntaxhighlight lang="bqn">data←•FBytes "input.txt" |
|||
"output.txt" •FBytes data</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
|||
<syntaxhighlight lang="bracmat">put$(get$"input.txt","output.txt",NEW)</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
int main(int argc, char **argv) { |
int main(int argc, char **argv) { |
||
Line 210: | Line 1,321: | ||
fclose(in); |
fclose(in); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
A couple of remarks on the preceding example: |
A couple of remarks on the preceding example: |
||
It uses < |
It uses <code>fgetc</code> to read one character at a time. Each character is visited, even though there's nothing to do with it. Copying bigger blocks of data is much more efficient. |
||
The following example addresses those issues. To avoid buffered I/O, it uses ''open()'', ''read()'', ''write()'' and ''close()'', which are part of [[POSIX]]. |
|||
It uses buffered IO to perform the move, which is overkill. This is not actually a weakness, but it invokes some overhead that you don't need. |
|||
The following example addresses those issues. To avoid buffered IO, it uses ''open()'', ''read()'', ''write()'' and ''close()'', which are part of [[POSIX]], but not defined of [[ANSI C]]. |
|||
{{works with|POSIX}} |
{{works with|POSIX}} |
||
< |
<syntaxhighlight lang="c">#include <unistd.h> |
||
#include <unistd.h> |
|||
#include <fcntl.h> |
#include <fcntl.h> |
||
#include <sys/types.h> |
|||
#include <sys/stat.h> |
|||
/* we just return a yes/no status; caller can check errno */ |
|||
int main(int argc, char **argv) |
|||
int copy_file(const char *in, const char *out) |
|||
{ int fi, fo; |
|||
{ |
|||
int len; |
|||
int ret = 0; |
|||
char buf[1024]; /* a better choice is the FS block size, if you know it */ |
|||
int fin, fout; |
|||
ssize_t len; |
|||
char *buf[4096]; /* buffer size, some multiple of block size preferred */ |
|||
struct stat st; |
|||
if ((fin = open(in, O_RDONLY)) == -1) return 0; |
|||
if (fstat(fin, &st)) goto bail; |
|||
perror("Can't read input.txt"); |
|||
return 1; |
|||
} |
|||
/* open output with same permission */ |
|||
if ((fo = open("output.txt", O_WRONLY|O_CREAT|O_TRUNC)) < 0) { |
|||
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777); |
|||
perror("Can't write to output.txt"); |
|||
if (fout == -1) goto bail; |
|||
} |
|||
while ((len = read(fin, buf, 4096)) > 0) |
|||
write(fout, buf, len); |
|||
perror("write failed"); |
|||
return 1; |
|||
} |
|||
} |
|||
ret = len ? 0 : 1; /* last read should be 0 */ |
|||
if (len < 0) { |
|||
perror("read failed"); |
|||
return 1; |
|||
} |
|||
bail: if (fin != -1) close(fin); |
|||
if (fout != -1) close(fout); |
|||
return 0; |
|||
return ret; |
|||
}</lang> |
|||
} |
|||
int main() |
|||
{ |
|||
copy_file("infile", "outfile"); |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
If it's certain that mapping the whole input file into memory poses no problem (there can be all kinds of problems), this may be the most efficient:<syntaxhighlight lang="c">int copy_file(const char *in, const char *out) |
|||
{ |
|||
int ret = 0; |
|||
int fin, fout; |
|||
char *bi; |
|||
struct stat st; |
|||
if ((fin = open(in, O_RDONLY)) == -1) return 0; |
|||
if (fstat(fin, &st)) goto bail; |
|||
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777); |
|||
if (fout == -1) goto bail; |
|||
bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin, 0); |
|||
ret = (bi == (void*)-1) |
|||
? 0 : (write(fout, bi, st.st_size) == st.st_size); |
|||
bail: if (fin != -1) close(fin); |
|||
if (fout != -1) close(fout); |
|||
if (bi != (void*)-1) munmap(bi, st.st_size); |
|||
return ret; |
|||
}</syntaxhighlight> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
Line 260: | Line 1,395: | ||
The long way: |
The long way: |
||
< |
<syntaxhighlight lang="csharp">using System.IO; |
||
using (var reader = new StreamReader("input.txt")) |
using (var reader = new StreamReader("input.txt")) |
||
Line 267: | Line 1,402: | ||
var text = reader.ReadToEnd(); |
var text = reader.ReadToEnd(); |
||
writer.Write(text); |
writer.Write(text); |
||
}</ |
}</syntaxhighlight> |
||
The short way: |
The short way: |
||
< |
<syntaxhighlight lang="csharp">using System.IO; |
||
var text = File.ReadAllText("input.txt"); |
var text = File.ReadAllText("input.txt"); |
||
File.WriteAllText("output.txt", text);</ |
File.WriteAllText("output.txt", text);</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{works with|g++|3.4.2}} |
{{works with|g++|3.4.2}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <fstream> |
#include <fstream> |
||
#include <string> |
#include <string> |
||
Line 305: | Line 1,440: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Simpler version: |
Simpler version: |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <fstream> |
#include <fstream> |
||
#include <cstdlib> |
#include <cstdlib> |
||
Line 337: | Line 1,472: | ||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
Using istream- and ostream- iterators: |
Using istream- and ostream- iterators: |
||
< |
<syntaxhighlight lang="cpp"># include <algorithm> |
||
# include <fstream> |
# include <fstream> |
||
Line 350: | Line 1,485: | ||
std::istreambuf_iterator<char>(), |
std::istreambuf_iterator<char>(), |
||
std::ostreambuf_iterator<char>(ofile)); |
std::ostreambuf_iterator<char>(ofile)); |
||
}</ |
}</syntaxhighlight> |
||
Even simpler way: |
Even simpler way: |
||
< |
<syntaxhighlight lang="cpp">#include <fstream> |
||
int main() |
int main() |
||
Line 361: | Line 1,496: | ||
std::ofstream output("output.txt"); |
std::ofstream output("output.txt"); |
||
output << input.rdbuf(); |
output << input.rdbuf(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
Define a function that copies the content from one file to another. |
Define a function that copies the content from one file to another. |
||
< |
<syntaxhighlight lang="clean">import StdEnv |
||
copyFile fromPath toPath world |
copyFile fromPath toPath world |
||
Line 384: | Line 1,519: | ||
# toFile = fwrites buffer toFile |
# toFile = fwrites buffer toFile |
||
| size buffer < bufferSize = (fromFile, toFile) // we're done |
| size buffer < bufferSize = (fromFile, toFile) // we're done |
||
= copyData bufferSize fromFile toFile // continue recursively</ |
= copyData bufferSize fromFile toFile // continue recursively</syntaxhighlight> |
||
Apply this function to the world to copy a file. |
Apply this function to the world to copy a file. |
||
< |
<syntaxhighlight lang="clean">Start world = copyFile "input.txt" "output.txt" world</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(use 'clojure.java.io) |
(use 'clojure.java.io) |
||
(copy (file "input.txt") (file "output.txt")) |
(copy (file "input.txt") (file "output.txt")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="lisp"> |
||
;; simple file writing |
;; simple file writing |
||
(spit "filename.txt" "your content here") |
(spit "filename.txt" "your content here") |
||
Line 403: | Line 1,538: | ||
;; simple file reading |
;; simple file reading |
||
(slurp "filename.txt") |
(slurp "filename.txt") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
|||
===COBOL 85=== |
|||
{{works with|COBOL 85 standard}} |
|||
Flags used for Micro Focus COBOL: |
|||
$set ans85 flag"ans85" flagas"s" sequential"line" |
|||
<syntaxhighlight lang="cobol"> identification division. |
|||
program-id. copyfile. |
|||
environment division. |
|||
input-output section. |
|||
file-control. |
|||
select input-file assign to "input.txt" |
|||
organization sequential |
|||
. |
|||
select output-file assign to "output.txt" |
|||
organization sequential |
|||
. |
|||
data division. |
|||
file section. |
|||
fd input-file. |
|||
1 input-record pic x(80). |
|||
fd output-file. |
|||
1 output-record pic x(80). |
|||
working-storage section. |
|||
1 end-of-file-flag pic 9 value 0. |
|||
88 eof value 1. |
|||
1 text-line pic x(80). |
|||
procedure division. |
|||
begin. |
|||
open input input-file |
|||
output output-file |
|||
perform read-input |
|||
perform until eof |
|||
write output-record from text-line |
|||
perform read-input |
|||
end-perform |
|||
close input-file output-file |
|||
stop run |
|||
. |
|||
read-input. |
|||
read input-file into text-line |
|||
at end |
|||
set eof to true |
|||
end-read |
|||
. |
|||
end program copyfile. </syntaxhighlight> |
|||
===Implementation=== |
|||
{{works with|OpenCOBOL}} |
|||
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. file-io. |
|||
ENVIRONMENT DIVISION. |
|||
INPUT-OUTPUT SECTION. |
|||
FILE-CONTROL. |
|||
SELECT in-file ASSIGN "input.txt" |
|||
ORGANIZATION LINE SEQUENTIAL. |
|||
SELECT OPTIONAL out-file ASSIGN "output.txt" |
|||
ORGANIZATION LINE SEQUENTIAL. |
|||
DATA DIVISION. |
|||
FILE SECTION. |
|||
FD in-file. |
|||
01 in-line PIC X(256). |
|||
FD out-file. |
|||
01 out-line PIC X(256). |
|||
PROCEDURE DIVISION. |
|||
DECLARATIVES. |
|||
in-file-error SECTION. |
|||
USE AFTER ERROR ON in-file. |
|||
DISPLAY "An error occurred while using input.txt." |
|||
GOBACK |
|||
. |
|||
out-file-error SECTION. |
|||
USE AFTER ERROR ON out-file. |
|||
DISPLAY "An error occurred while using output.txt." |
|||
GOBACK |
|||
. |
|||
END DECLARATIVES. |
|||
mainline. |
|||
OPEN INPUT in-file |
|||
OPEN OUTPUT out-file |
|||
PERFORM FOREVER |
|||
READ in-file |
|||
AT END |
|||
EXIT PERFORM |
|||
END-READ |
|||
WRITE out-line FROM in-line |
|||
END-PERFORM |
|||
CLOSE in-file, out-file |
|||
.</syntaxhighlight> |
|||
===Built-in Subroutines=== |
|||
{{works with|OpenCOBOL}} |
|||
{{works with|Visual COBOL}} |
|||
<syntaxhighlight lang="cobol">*> Originally from ACUCOBOL-GT |
|||
CALL "C$COPY" USING "input.txt", "output.txt", 0</syntaxhighlight> |
|||
<syntaxhighlight lang="cobol">*> Originally from Micro Focus COBOL |
|||
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"</syntaxhighlight> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="cfm"><cfif fileExists(expandPath("input.txt"))> |
||
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents"> |
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents"> |
||
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#"> |
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#"> |
||
</cfif></ |
</cfif></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 416: | Line 1,655: | ||
By lines: |
By lines: |
||
< |
<syntaxhighlight lang="lisp">(with-open-file (in #p"input.txt" :direction :input) |
||
(with-open-file (out #p"output.txt" :direction :output) |
(with-open-file (out #p"output.txt" :direction :output) |
||
(loop for line = (read-line in nil 'foo) |
(loop for line = (read-line in nil 'foo) |
||
until (eq line 'foo) |
until (eq line 'foo) |
||
do (write-line line out))))</ |
do (write-line line out))))</syntaxhighlight> |
||
By arbitrary blocks and for possibly-binary files: |
By arbitrary blocks and for possibly-binary files: |
||
< |
<syntaxhighlight lang="lisp">(defconstant +buffer-size+ (expt 2 16)) |
||
(with-open-file (in #p"input.txt" :direction :input |
(with-open-file (in #p"input.txt" :direction :input |
||
Line 435: | Line 1,674: | ||
for size = (read-sequence buffer in) |
for size = (read-sequence buffer in) |
||
while (plusp size) |
while (plusp size) |
||
do (write-sequence buffer out :end size))))</ |
do (write-sequence buffer out :end size))))</syntaxhighlight> |
||
If you're on an odd platform which actually stores text/binary/... type information for files and your CL implementation will use this information, then <tt>in</tt> should be opened with <tt>:element-type :default</tt>. |
If you're on an odd platform which actually stores text/binary/... type information for files and your CL implementation will use this information, then <tt>in</tt> should be opened with <tt>:element-type :default</tt>. |
||
=={{header|D}}== |
=={{header|D}}== |
||
{{libheader|Phobos}} |
|||
{{works with|D|2}} |
{{works with|D|2}} |
||
< |
<syntaxhighlight lang="d">import std.file: copy; |
||
void main() { |
void main() { |
||
copy("input.txt", "output.txt"); |
copy("input.txt", "output.txt"); |
||
}</ |
}</syntaxhighlight> |
||
very plainly, with an intermediate variable: |
|||
<syntaxhighlight lang="d"> |
|||
void main() { |
|||
import std.file; |
|||
auto data = std.file.read("input.txt"); |
|||
std.file.write("output.txt", data); |
|||
} |
|||
</syntaxhighlight> |
|||
via an intermediate buffer variable: |
|||
<syntaxhighlight lang="d">import std.stdio; |
|||
int main() { |
|||
auto from = File("input.txt", "rb"); |
|||
scope(exit) from.close(); |
|||
auto to = File("output.txt", "wb"); |
|||
scope(exit) to.close(); |
|||
foreach(buffer; from.byChunk(new ubyte[4096*1024])) { |
|||
to.rawWrite(buffer); |
|||
} |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
{{libheader|Tango}} |
{{libheader|Tango}} |
||
Line 451: | Line 1,717: | ||
Copy the content from one file to another (exceptions are handled by Tango): |
Copy the content from one file to another (exceptions are handled by Tango): |
||
< |
<syntaxhighlight lang="d">import tango.io.device.File; |
||
void main() |
void main() |
||
Line 459: | Line 1,725: | ||
to.copy(from).close; |
to.copy(from).close; |
||
from.close; |
from.close; |
||
}</ |
}</syntaxhighlight> |
||
Or a shorter example without explicitly closing the output file: |
Or a shorter example without explicitly closing the output file: |
||
< |
<syntaxhighlight lang="d">import tango.io.device.File; |
||
void main() |
void main() |
||
Line 467: | Line 1,733: | ||
auto to = new File("output.txt", File.WriteCreate); |
auto to = new File("output.txt", File.WriteCreate); |
||
to.copy(new File("input.txt")).close; |
to.copy(new File("input.txt")).close; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|DBL}}== |
|||
<syntaxhighlight lang="dbl">; |
|||
; File Input and output examples for DBL version 4 by Dario B. |
|||
; |
|||
RECORD CUSTOM |
|||
CUCOD, D5 ;customer code |
|||
CUNAM, A20 ;name |
|||
CUCIT, A20 ;city |
|||
, A55 |
|||
;------- 100 bytes ------------- |
|||
A80, A80 |
|||
PROC |
|||
;-------------------------------------------------------------- |
|||
XCALL FLAGS (0007000000,1) ;suppress STOP message |
|||
CLOSE 1 |
|||
OPEN (1,O,'TT:') ;open video |
|||
CLOSE 2 |
|||
OPEN (2,O,"CUSTOM.DDF") ;create file in output |
|||
;Add new record |
|||
CLEAR CUSTOM |
|||
CUCOD=1 |
|||
CUNAM="Alan Turing" |
|||
CUCIT="London" |
|||
WRITES (2,CUSTOM) |
|||
;Add new record |
|||
CLEAR CUSTOM |
|||
CUCOD=2 |
|||
CUNAM="Galileo Galilei" |
|||
CUCIT="Pisa" |
|||
WRITES (2,CUSTOM) |
|||
;Modify a record |
|||
CLOSE 2 |
|||
OPEN (2,U,"CUSTOM.DDF") [ERR=NOCUS] ;open in update |
|||
READ (2,CUSTOM,2) [ERR=NOREC] |
|||
CUCIT="Pisa - Italy" |
|||
WRITE (2,CUSTOM,2) [ERR=NOWRI] |
|||
;Add new record |
|||
CLOSE 2 |
|||
OPEN (2,A,"CUSTOM.DDF") [ERR=NOCUS] ;open in append |
|||
CLEAR CUSTOM |
|||
CUCOD=3 |
|||
CUNAM="Kenneth Lane Thompson" |
|||
CUCIT="New Orleans" |
|||
WRITES (2,CUSTOM) |
|||
CLOSE 2 |
|||
;Read file and display a video |
|||
CLOSE 2 |
|||
OPEN (2,I,"CUSTOM.DDF") [ERR=NOCUS] |
|||
DO FOREVER |
|||
BEGIN |
|||
READS (2,CUSTOM,EOF) [ERR=NOREC] |
|||
DISPLAY (1,13,CUSTOM) |
|||
END |
|||
EOF, DISPLAY (1,10) |
|||
CLOSE 2 |
|||
;Write/read a text file |
|||
CLOSE 3 |
|||
OPEN (3,O,"FILE.TXT") |
|||
DISPLAY (3,"An Occurrence at Owl Creek Bridge",13,10) |
|||
DISPLAY (3,"A man stood upon a railroad bridge in northern Alabama,",13,10) |
|||
DISPLAY (3,"looking down into the swift water twenty feet below.",13,10) |
|||
DISPLAY (3,"The man's hands were behind his back, the wrists bound ") |
|||
DISPLAY (3,"with a cord.",13,10) |
|||
CLOSE 3 |
|||
OPEN (3,I,"FILE.TXT") |
|||
DO FOREVER |
|||
BEGIN |
|||
READS (3,A80,EOFF) |
|||
DISPLAY (1,A80(1:%TRIM(A80)),10) |
|||
END |
|||
EOFF, CLOSE 3 |
|||
DISPLAY (1,10) |
|||
GOTO QUIT |
|||
;--------------------------------------------------------------- |
|||
NOCUS, DISPLAY (1,10,"File CUSTUM.DDF Not found!",10) |
|||
GOTO QUIT |
|||
NOREC, DISPLAY (1,10,"Read error!",10) |
|||
GOTO QUIT |
|||
NOWRI, DISPLAY (1,10,"Write error!",10) |
|||
GOTO QUIT |
|||
QUIT, CLOSE 1 |
|||
STOP</syntaxhighlight> |
|||
{{out}} |
|||
<pre>00001Alan Turing London |
|||
00002Galileo Galilei Pisa - Italy |
|||
00003Kenneth Lane ThompsoNew Orleans |
|||
An Occurrence at Owl Creek Bridge |
|||
A man stood upon a railroad bridge in northern Alabama, |
|||
looking down into the swift water twenty feet below. |
|||
The man's hands were behind his back, the wrists bound with a cord.</pre> |
|||
=={{header|DCL}}== |
|||
<syntaxhighlight lang="dcl">$ open input input.txt |
|||
$ open /write output output.txt |
|||
$ loop: |
|||
$ read /end_of_file = done input line |
|||
$ write output line |
|||
$ goto loop |
|||
$ done: |
|||
$ close input |
|||
$ close output</syntaxhighlight> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 504: | Line 1,892: | ||
'''- Text File I/O -''' |
'''- Text File I/O -''' |
||
< |
<syntaxhighlight lang="delphi">var |
||
f : TextFile ; |
f : TextFile ; |
||
s : string ; |
s : string ; |
||
Line 514: | Line 1,902: | ||
ReadLn(F,S); |
ReadLn(F,S); |
||
CloseFile( |
CloseFile( |
||
end;</ |
end;</syntaxhighlight> |
||
Line 521: | Line 1,909: | ||
This is perhaps one of the most powerful I/O functions built into Pascal. This will allow you to open and read a file of ANY type, regardless of structure, size or content. Note the usage of Reset(). This is using the optional size parameter that instructs the record size of file I/O. This could have been called with SizeOf(Buff) as the optional parameter but that would have limited flexibility. Calling it with a size of ONE byte allows you to adjust the buffer size on the fly, as conditions warrant. Also note the use of the BytesRead parameter. When included in the BlockRead() function it will return the number of bytes actually read. If this is not included, then if your directive to read n bytes is greater then the size of the file, the EOF will be encountered unexpectedly and EIOError will be raised. |
This is perhaps one of the most powerful I/O functions built into Pascal. This will allow you to open and read a file of ANY type, regardless of structure, size or content. Note the usage of Reset(). This is using the optional size parameter that instructs the record size of file I/O. This could have been called with SizeOf(Buff) as the optional parameter but that would have limited flexibility. Calling it with a size of ONE byte allows you to adjust the buffer size on the fly, as conditions warrant. Also note the use of the BytesRead parameter. When included in the BlockRead() function it will return the number of bytes actually read. If this is not included, then if your directive to read n bytes is greater then the size of the file, the EOF will be encountered unexpectedly and EIOError will be raised. |
||
< |
<syntaxhighlight lang="delphi">var |
||
f : File ; |
f : File ; |
||
buff : array[1.1024] of byte ; |
buff : array[1.1024] of byte ; |
||
Line 530: | Line 1,918: | ||
Blockread(f,Buff,SizeOf(Buff),BytesRead); |
Blockread(f,Buff,SizeOf(Buff),BytesRead); |
||
CloseFile(f); |
CloseFile(f); |
||
end;</ |
end;</syntaxhighlight> |
||
'''- Typed File I/O -''' |
'''- Typed File I/O -''' |
||
Line 536: | Line 1,924: | ||
Typed file I/O is very useful when reading and writing structures. An Address List is quiet easy to write when using this type of I/O. The same file procedures are used with some subtle differences. Bite below in the blockread and blockwrite procedures that the bytes to read or write are 1. Also note that the reset procedure is not called with a buffer size. When performing '''Typed File I/O''' the size of the type definition is the buffer size. In the BlockRead() and BlockWrite() procedures I elected to read '''one record'''. Had I declared a very large buffer of type tAddressBook of say 500 records, I could have set bytes to read as SizeOf(Buffer) thereby reading a minimum of 500 records. |
Typed file I/O is very useful when reading and writing structures. An Address List is quiet easy to write when using this type of I/O. The same file procedures are used with some subtle differences. Bite below in the blockread and blockwrite procedures that the bytes to read or write are 1. Also note that the reset procedure is not called with a buffer size. When performing '''Typed File I/O''' the size of the type definition is the buffer size. In the BlockRead() and BlockWrite() procedures I elected to read '''one record'''. Had I declared a very large buffer of type tAddressBook of say 500 records, I could have set bytes to read as SizeOf(Buffer) thereby reading a minimum of 500 records. |
||
< |
<syntaxhighlight lang="delphi">type |
||
tAddressBook = Record |
tAddressBook = Record |
||
Line 562: | Line 1,950: | ||
BlockWrite(f,v,1,bytes); |
BlockWrite(f,v,1,bytes); |
||
CloseFile(f); |
CloseFile(f); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|DIBOL-11}}== |
|||
<syntaxhighlight lang="dibol-11"> |
|||
START ;Simple File Input and Output |
|||
RECORD TEMP |
|||
INLINE, A72 |
|||
PROC |
|||
OPEN (8,I,"input.txt") |
|||
OPEN (9,O,"output.txt") |
|||
LOOP, |
|||
READS(8,TEMP,END) |
|||
WRITES(9,TEMP) |
|||
GOTO LOOP |
|||
END, |
|||
CLOSE 8 |
|||
CLOSE 9 |
|||
END |
|||
</syntaxhighlight> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
{{works with|E-on-Java}} |
{{works with|E-on-Java}} |
||
< |
<syntaxhighlight lang="e"><file:output.txt>.setText(<file:input.txt>.getText())</syntaxhighlight> |
||
(This version holds the entire contents in memory.) |
(This version holds the entire contents in memory.) |
||
Line 572: | Line 1,985: | ||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel ">class |
||
APPLICATION |
APPLICATION |
||
Line 604: | Line 2,017: | ||
output_file: PLAIN_TEXT_FILE |
output_file: PLAIN_TEXT_FILE |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elena}}== |
|||
ELENA 4.x : |
|||
<syntaxhighlight lang="elena">import system'io; |
|||
public program() |
|||
{ |
|||
var text := File.assign("input.txt").readContent(); |
|||
File.assign("output.txt").saveContent(text); |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
Read in the whole file and write the contents to a new file. |
|||
<syntaxhighlight lang="elixir">defmodule FileReadWrite do |
|||
def copy(path,new_path) do |
|||
case File.read(path) do |
|||
# In case of success, write to the new file |
|||
{:ok, body} -> |
|||
# Can replace with :write! to generate an error upon failure |
|||
File.write(new_path,body) |
|||
# If not successful, raise an error |
|||
{:error,reason} -> |
|||
# Using Erlang's format_error to generate error string |
|||
:file.format_error(reason) |
|||
end |
|||
end |
|||
end |
|||
FileReadWrite.copy("input.txt","output.txt")</syntaxhighlight> |
|||
'''Built in function:''' |
|||
<syntaxhighlight lang="elixir">File.cp!("input.txt", "output.txt")</syntaxhighlight> |
|||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp">(defvar input (with-temp-buffer |
|||
(insert-file-contents "input.txt") |
|||
(buffer-string))) |
|||
(with-temp-file "output.txt" |
|||
(insert input)) |
|||
</syntaxhighlight> |
|||
=={{header|Erlang}}== |
|||
<syntaxhighlight lang="erlang"> |
|||
-module( file_io ). |
|||
-export( [task/0] ). |
|||
task() -> |
|||
{ok, Contents} = file:read_file( "input.txt" ), |
|||
ok = file:write_file( "output.txt", Contents ). |
|||
</syntaxhighlight> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
===Read the entire file and then write it=== |
===Read the entire file and then write it=== |
||
{{works with|Euphoria|4.0.0}} |
{{works with|Euphoria|4.0.0}} |
||
< |
<syntaxhighlight lang="euphoria">include std/io.e |
||
write_lines("output.txt", read_lines("input.txt"))</ |
write_lines("output.txt", read_lines("input.txt"))</syntaxhighlight> |
||
===Line-by-line reading and writing=== |
===Line-by-line reading and writing=== |
||
{{works with|Euphoria|any}} |
{{works with|Euphoria|any}} |
||
< |
<syntaxhighlight lang="euphoria">integer in,out |
||
object line |
object line |
||
Line 629: | Line 2,097: | ||
close(out) |
close(out) |
||
close(in)</ |
close(in)</syntaxhighlight> |
||
=={{header|Erlang}}== |
|||
This version uses the built-in function file:copy/2. |
|||
<lang erlang>file:copy("input.txt","output.txt").</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless... |
|||
< |
<syntaxhighlight lang="fsharp">open System.IO |
||
let copyFile fromTextFileName toTextFileName = |
|||
let read = File.ReadAllText |
|||
let inputContent = File.ReadAllText fromTextFileName |
|||
let write file text = File.WriteAllText(file, text) |
|||
inputContent |> fun text -> File.WriteAllText(toTextFileName, text) |
|||
[<EntryPoint>] |
|||
"input.txt" |> read |> write "output.txt" |
|||
let main argv = |
|||
</lang> |
|||
copyFile "input.txt" "output.txt" |
|||
0 |
|||
</syntaxhighlight> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Holds entire file content in memory: |
Holds entire file content in memory: |
||
< |
<syntaxhighlight lang="factor">"input.txt" binary file-contents |
||
"output.txt" binary set-file-contents</ |
"output.txt" binary set-file-contents</syntaxhighlight> |
||
A bit longer, but only holds a small amount of data in memory. If opening the file for writing fails, we want to clean up the file that's open for reading: |
A bit longer, but only holds a small amount of data in memory. If opening the file for writing fails, we want to clean up the file that's open for reading: |
||
< |
<syntaxhighlight lang="factor">[ |
||
"input.txt" binary <file-reader> &dispose |
"input.txt" binary <file-reader> &dispose |
||
"output.txt" binary <file-writer> stream-copy |
"output.txt" binary <file-writer> stream-copy |
||
] with-destructors |
] with-destructors |
||
</syntaxhighlight> |
|||
</lang> |
|||
Possibly cheating: |
Possibly cheating: |
||
< |
<syntaxhighlight lang="factor">"input.txt" "output.txt" copy-file</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 662: | Line 2,131: | ||
Forth traditionally has not had any file handling capabilities, preferring instead to operate on a disk image block by block. Most modern Forth systems however run under an existing operating system and provide methods for disk access. |
Forth traditionally has not had any file handling capabilities, preferring instead to operate on a disk image block by block. Most modern Forth systems however run under an existing operating system and provide methods for disk access. |
||
< |
<syntaxhighlight lang="forth">\ <to> <from> copy-file |
||
: copy-file ( a1 n1 a2 n2 -- ) |
: copy-file ( a1 n1 a2 n2 -- ) |
||
r/o open-file throw >r |
r/o open-file throw >r |
||
w/o create-file throw r> |
w/o create-file throw r> |
||
begin |
begin |
||
pad |
pad 84 2 pick read-file throw |
||
?dup while |
?dup while |
||
pad swap 3 pick write-file throw |
pad swap 3 pick write-file throw |
||
repeat |
repeat |
||
Line 675: | Line 2,144: | ||
\ Invoke it like this: |
\ Invoke it like this: |
||
s" output.txt" s" input.txt" copy-file</ |
s" output.txt" s" input.txt" copy-file</syntaxhighlight> |
||
Note the use of "2 pick" to get the input file handle and "3 pick" to get the output file handle. Local or global variables could have been used, but in this implementation simple stack manipulation was chosen. Also, only |
Note the use of "2 pick" to get the input file handle and "3 pick" to get the output file handle. Local or global variables could have been used, but in this implementation simple stack manipulation was chosen. Also, only 84 bytes are copied at a time, as that is the maximum guaranteed size of "pad" the global memory area used to hold the data. For faster copies, allocating a larger buffer could be advantageous. |
||
Also, abort" can be used instead of throw if desired. |
Also, abort" can be used instead of throw if desired. |
||
A good practice is to ask the user the file name he wants to create like in this short example |
|||
<syntaxhighlight lang="text">: INPUT$ ( text -- n n ) |
|||
pad swap accept pad swap ; |
|||
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out |
|||
: get-content cr ." Enter your nickname : " 20 INPUT$ fd-out write-file cr ; |
|||
: close-output ( -- ) fd-out close-file throw ; |
|||
get-content |
|||
\ Inject a carriage return at end of file |
|||
s\" \n" fd-out write-file |
|||
close-output |
|||
bye</syntaxhighlight> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|2003}} |
{{works with|Fortran|2003}} |
||
{{works with|gfortran|4.3.2}} |
|||
It uses the <tt>access="stream"</tt> which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily. |
It uses the <tt>access="stream"</tt> which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily. |
||
< |
<syntaxhighlight lang="fortran">program FileIO |
||
integer, parameter :: out = 123, in = 124 |
integer, parameter :: out = 123, in = 124 |
||
integer :: err |
integer :: err |
||
character |
character :: c |
||
open(out, file="output.txt", status="new", action="write", access="stream", iostat=err) |
open(out, file="output.txt", status="new", action="write", access="stream", iostat=err) |
||
if ( |
if (err == 0) then |
||
open(in, file="input.txt", status="old", action="read", access="stream", iostat=err) |
open(in, file="input.txt", status="old", action="read", access="stream", iostat=err) |
||
if ( |
if (err == 0) then |
||
err = 0 |
err = 0 |
||
do while ( |
do while (err == 0) |
||
read(unit=in, iostat=err) c |
read(unit=in, iostat=err) c |
||
if ( |
if (err == 0) write(out) c |
||
end do |
end do |
||
close(in) |
close(in) |
||
Line 707: | Line 2,186: | ||
end if |
end if |
||
end program FileIO</ |
end program FileIO</syntaxhighlight> |
||
=={{header|Frink}}== |
|||
<syntaxhighlight lang="frink"> |
|||
contents = read["file:input.txt"] |
|||
w = new Writer["output.txt"] |
|||
w.print[contents] |
|||
w.close[] |
|||
</syntaxhighlight> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">CopyFile := function(src, dst) |
||
local f, g, line; |
local f, g, line; |
||
f := InputTextFile(src); |
f := InputTextFile(src); |
||
Line 723: | Line 2,211: | ||
CloseStream(f); |
CloseStream(f); |
||
CloseStream(g); |
CloseStream(g); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|GML}}== |
=={{header|GML}}== |
||
<syntaxhighlight lang="gml">var file, str; |
|||
<lang GML>file_copy("input.txt","output.txt")</lang> |
|||
file = file_text_open_read("input.txt"); |
|||
str = ""; |
|||
while (!file_text_eof(file)) |
|||
{ |
|||
str += file_text_read_string(file); |
|||
if (!file_text_eof(file)) |
|||
{ |
|||
str += " |
|||
"; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind |
|||
file_text_readln(file); |
|||
} |
|||
} |
|||
file_text_close(file); |
|||
file = file_text_open_write("output.txt"); |
|||
file_text_write_string(file,str); |
|||
file_text_close(file);</syntaxhighlight> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
|||
"fmt" |
|||
"io/ioutil" |
|||
) |
|||
func main() { |
|||
b, err := ioutil.ReadFile("input.txt") |
|||
if err != nil { |
|||
fmt.Println(err) |
|||
return |
|||
} |
|||
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { |
|||
fmt.Println(err) |
|||
} |
|||
}</syntaxhighlight> |
|||
Alternative solution is not a one-liner, but is one of "secondary interest" that copies data from one file to another without an intermediate variable. |
|||
<syntaxhighlight lang="go">package main |
|||
import ( |
import ( |
||
"log" |
|||
"io" |
"io" |
||
"log" |
|||
"os" |
"os" |
||
) |
) |
||
func CopyFile(out, in string) (err |
func CopyFile(out, in string) (err error) { |
||
var inf, outf *os.File |
var inf, outf *os.File |
||
inf, err = os.Open(in) |
|||
if err != nil { |
|||
return |
|||
if outf, err = os.Create(out); err == nil { |
|||
} |
|||
defer outf.Close() |
|||
defer func() { |
|||
_, err = io.Copy(outf, inf) |
|||
cErr := inf.Close() |
|||
if err == nil { |
|||
err = cErr |
|||
} |
} |
||
}() |
|||
outf, err = os.Create(out) |
|||
if err != nil { |
|||
return |
|||
} |
|||
_, err = io.Copy(outf, inf) |
|||
cErr := outf.Close() |
|||
if err == nil { |
|||
err = cErr |
|||
} |
} |
||
return |
return |
||
Line 753: | Line 2,288: | ||
log.Fatal(err) |
log.Fatal(err) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Using File |
Using File |
||
< |
<syntaxhighlight lang="groovy">content = new File('input.txt').text |
||
new File('output.txt').write(content)</syntaxhighlight> |
|||
Using Ant |
Using Ant |
||
< |
<syntaxhighlight lang="groovy">new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)</syntaxhighlight> |
||
Buffered |
Buffered |
||
< |
<syntaxhighlight lang="groovy">new File('output.txt').withWriter( w -> |
||
new File('input.txt').withReader( r -> w << r } |
new File('input.txt').withReader( r -> w << r } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|GUISS}}== |
|||
<syntaxhighlight lang="guiss">Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste, |
|||
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]</syntaxhighlight> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation. |
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation. |
||
< |
<syntaxhighlight lang="haskell">main = readFile "input.txt" >>= writeFile "output.txt"</syntaxhighlight> |
||
=={{header|hexiscript}}== |
|||
<syntaxhighlight lang="hexiscript">let in openin "input.txt" |
|||
let out openout "output.txt" |
|||
while !(catch (let c read char in)) |
|||
write c out |
|||
endwhile |
|||
close in; close out</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
Copy via system call: |
Copy via system call: |
||
< |
<syntaxhighlight lang="hicest">CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096 |
||
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)</ |
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)</syntaxhighlight> |
||
Read and write line by line |
Read and write line by line |
||
< |
<syntaxhighlight lang="hicest">OPEN(FIle=input, OLD, ERror=21) ! on error branch to label 21 (not shown) |
||
OPEN(FIle=output) |
OPEN(FIle=output) |
||
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error |
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error |
||
Line 783: | Line 2,332: | ||
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown) |
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown) |
||
ENDDO |
ENDDO |
||
22 WRITE(FIle=output, CLoSe=1)</ |
22 WRITE(FIle=output, CLoSe=1)</syntaxhighlight> |
||
Read and write in 1 block |
Read and write in 1 block |
||
< |
<syntaxhighlight lang="hicest">OPEN(FIle=input, SEQuential, UNFormatted, OLD, LENgth=len, ERror=31) ! on error branch to label 31 (not shown) |
||
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown) |
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown) |
||
ALLOCATE(c, len) |
ALLOCATE(c, len) |
||
READ(FIle=input, CLoSe=1) c |
READ(FIle=input, CLoSe=1) c |
||
WRITE(FIle=output, CLoSe=1) c END</ |
WRITE(FIle=output, CLoSe=1) c END</syntaxhighlight> |
||
=={{header|i}}== |
|||
<syntaxhighlight lang="i">software { |
|||
file = load("input.txt") |
|||
open("output.txt").write(file) |
|||
} </syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Icon and Unicon I/O by default is line driven. This can be changed with options in open and by the use of reads() and writes(). |
Icon and Unicon I/O by default is line driven. This can be changed with options in open and by the use of reads() and writes(). |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
in := open(f := "input.txt","r") | stop("Unable to open ",f) |
in := open(f := "input.txt","r") | stop("Unable to open ",f) |
||
out := open(f := "output.txt","w") | stop("Unable to open ",f) |
out := open(f := "output.txt","w") | stop("Unable to open ",f) |
||
while write(out,read(in)) |
while write(out,read(in)) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
< |
<syntaxhighlight lang="idl">; open two LUNs |
||
openw,unit1,'output.txt,/get |
openw,unit1,'output.txt,/get |
||
openr,unit2,'input.txt',/get |
openr,unit2,'input.txt',/get |
||
Line 812: | Line 2,367: | ||
writeu,unit1,buff |
writeu,unit1,buff |
||
; that's all |
; that's all |
||
close,/all</ |
close,/all</syntaxhighlight> |
||
=={{header|Io}}== |
|||
<syntaxhighlight lang="io">inf := File with("input.txt") openForReading |
|||
outf := File with("output.txt") openForUpdating |
|||
while(l := inf readLine, |
|||
outf write(l, "\n") |
|||
) |
|||
inf close |
|||
outf close |
|||
</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> 'output.txt' (1!:2~ 1!:1)&< 'input.txt'</syntaxhighlight> |
||
Or using the system library <tt>files</tt>: |
Or using the system library <tt>files</tt>: |
||
< |
<syntaxhighlight lang="j">require 'files' |
||
'output.txt' (fwrite~ fread) 'input.txt'</ |
'output.txt' (fwrite~ fread) 'input.txt'</syntaxhighlight> |
||
Note that J will read as many characters from the file as the system reports, for the size of the file. So if the system reports that the file is empty when it is not, J will return an empty result when using this file reading mechanism. (This can happen for "files" which really represent a connection to something else. When this happens, it's usually better to dedicate a [[Execute_a_system_command#J|separate process]] to reading the file.) |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 828: | Line 2,398: | ||
Simple version; Files ''may'' be closed automatically by OS, on some systems. |
Simple version; Files ''may'' be closed automatically by OS, on some systems. |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
public class FileIODemo { |
public class FileIODemo { |
||
Line 845: | Line 2,415: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
This version closes both files after without OS intervention |
This version closes both files after without OS intervention. |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
public class FileIODemo2 { |
public class FileIODemo2 { |
||
Line 878: | Line 2,448: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|1.4}} |
{{works with|Java|1.4}} |
||
'''Package''' [[nio]] |
'''Package''' [[nio]] |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
import java.nio.channels.*; |
import java.nio.channels.*; |
||
Line 908: | Line 2,478: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
This version is more in line with the other languages' implementations: it assumes simple text files, and doesn't worry too much about errors (just throws them out to the caller, the console in this case). It's shorter and simpler and shows that simple programs can be simple to write, in Java as well. |
This version is more in line with the other languages' implementations: it assumes simple text files, and doesn't worry too much about errors (just throws them out to the caller, the console in this case). It's shorter and simpler and shows that simple programs can be simple to write, in Java as well. |
||
< |
<syntaxhighlight lang="java">import java.io.*; |
||
public class Test { |
public class Test { |
||
public static void main (String[] args) throws IOException { |
public static void main (String[] args) throws IOException { |
||
BufferedReader br = new BufferedReader(new FileReader("input.txt")); |
BufferedReader br = new BufferedReader(new FileReader("input.txt")); |
||
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); |
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); |
||
String line; |
|||
while ((line = br.readLine()) != null) { |
|||
bw.write(line); |
bw.write(line); |
||
bw.newLine(); |
bw.newLine(); |
||
Line 924: | Line 2,495: | ||
bw.close(); |
bw.close(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|7+}} |
|||
<syntaxhighlight lang="java5">import java.nio.file.*; |
|||
public class Copy{ |
|||
public static void main(String[] args) throws Exception{ |
|||
FileSystem fs = FileSystems.getDefault(); |
|||
Path in = fs.getPath("input.txt"); |
|||
Path out = fs.getPath("output.txt"); |
|||
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|JScript}} |
{{works with|JScript}} |
||
< |
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject"); |
||
var ForReading = 1, ForWriting = 2; |
var ForReading = 1, ForWriting = 2; |
||
var f_in = fso.OpenTextFile('input.txt', ForReading); |
var f_in = fso.OpenTextFile('input.txt', ForReading); |
||
Line 942: | Line 2,523: | ||
f_in.Close(); |
f_in.Close(); |
||
f_out.Close();</ |
f_out.Close();</syntaxhighlight> |
||
{{works with|Node.js}} |
|||
<syntaxhighlight lang="javascript"> |
|||
var fs = require('fs'); |
|||
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'})); |
|||
</syntaxhighlight> |
|||
=={{header|jq}}== |
|||
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows: |
|||
<syntaxhighlight lang="jq">jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt |
|||
</syntaxhighlight> |
|||
If the input file consists of JSON entities, and if we wish to "pretty print" each, then the following will suffice:<syntaxhighlight lang="jq"> |
|||
jq -M '. as $line | $line' input.txt > output.txt |
|||
</syntaxhighlight> |
|||
Note that the variable, $line, is included in the above programs solely to satisfy the task requirements. In practice, the jq program in both cases would normally be just: `.` |
|||
=={{header|Julia}}== |
|||
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2. |
|||
<syntaxhighlight lang="julia">mystring = read("file1", String) |
|||
open(io->write(io, mystring), "file2", "w")</syntaxhighlight> |
|||
Note however that Julia has a `cp` function to copy the content of a file to another file. |
|||
<syntaxhighlight lang="julia">cp("file1","file2")</syntaxhighlight> |
|||
We can also open and close the file handles manually. |
|||
<syntaxhighlight lang="julia">infile = open("file1", "r") |
|||
outfile = open("file2", "w") |
|||
write(outfile, read(infile, String)) |
|||
close(outfile) |
|||
close(infile)</syntaxhighlight> |
|||
Here is a one-liner that guarantees that the file handle is closed |
|||
even if something goes wrong during the read/write phase. |
|||
<syntaxhighlight lang="julia">open(IO ->write(IO, read("file1", String)), "file2", "w")</syntaxhighlight> |
|||
=={{header|K}}== |
=={{header|K}}== |
||
<lang>`output.txt 0:0:`input.txt</ |
<syntaxhighlight lang="k">`output.txt 0:0:`input.txt</syntaxhighlight> |
||
=={{header| |
=={{header|Kotlin}}== |
||
<lang lb>nomainwin |
|||
<syntaxhighlight lang="scala">// version 1.1.2 |
|||
open "input.txt" for input as #f1 |
|||
qtyBytes = lof( #f1) |
|||
import java.io.File |
|||
source$ = input$( #f1, qtyBytes) |
|||
close #f1 |
|||
fun main(args: Array<String>) { |
|||
val text = File("input.txt").readText() |
|||
File("output.txt").writeText(text) |
|||
}</syntaxhighlight> |
|||
=={{header|LabVIEW}}== |
|||
{{VI snippet}}<br/> |
|||
[[File:LabVIEW File IO.png]] |
|||
=={{header|Lang}}== |
|||
===Text-based=== |
|||
{{libheader|lang-io-module}} |
|||
<syntaxhighlight lang="lang"> |
|||
# Load the IO module |
|||
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">" |
|||
ln.loadModule(<pathToIO.lm>) |
|||
$fileIn = [[io]]::fp.openFile(input.txt) |
|||
$fileOut = [[io]]::fp.openFile(output.txt) |
|||
$text = [[io]]::fp.readFile($fileIn) |
|||
[[io]]::fp.writeFile($fileOut, $text) |
|||
[[io]]::fp.closeFile($fileIn) |
|||
[[io]]::fp.closeFile($fileOut) |
|||
</syntaxhighlight> |
|||
===Byte-based=== |
|||
{{libheader|lang-io-module}} |
|||
<syntaxhighlight lang="lang"> |
|||
# Load the IO module |
|||
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">" |
|||
ln.loadModule(<pathToIO.lm>) |
|||
$fileIn = [[io]]::fp.openFile(input.txt) |
|||
$fileOut = [[io]]::fp.openFile(output.txt) |
|||
$bytes = [[io]]::fp.readBytes($fileIn) |
|||
[[io]]::fp.writeBytes($fileOut, $bytes) |
|||
[[io]]::fp.closeFile($fileIn) |
|||
[[io]]::fp.closeFile($fileOut) |
|||
</syntaxhighlight> |
|||
=={{header|Lang5}}== |
|||
<syntaxhighlight lang="lang5">: puts(*) . "\n" . ; |
|||
: set-file '> swap open ; |
|||
: >>contents slurp puts ; |
|||
: copy-file |
|||
swap set-file 'fdst set fdst fout >>contents fdst close ; |
|||
'output.txt 'input.txt copy-file</syntaxhighlight> |
|||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">---------------------------------------- |
|||
-- Returns file as ByteArray |
|||
-- @param {string} tFile |
|||
-- @return {byteArray|false} |
|||
---------------------------------------- |
|||
on getBytes (tFile) |
|||
fp = xtra("fileIO").new() |
|||
fp.openFile(tFile, 1) |
|||
if fp.status() then return false |
|||
data = fp.readByteArray(fp.getLength()) |
|||
fp.closeFile() |
|||
return data |
|||
end |
|||
---------------------------------------- |
|||
open "output.txt" for output as #f2 |
|||
-- Saves ByteArray to file |
|||
#f2 source$; |
|||
-- @param {string} tFile |
|||
close #f2 |
|||
-- @param {byteArray} tString |
|||
-- @return {bool} success |
|||
---------------------------------------- |
|||
on putBytes (tFile, tByteArray) |
|||
fp = xtra("fileIO").new() |
|||
fp.openFile(tFile, 2) |
|||
err = fp.status() |
|||
if not (err) then fp.delete() |
|||
else if (err and not (err = -37)) then return false |
|||
fp.createFile(tFile) |
|||
if fp.status() then return false |
|||
fp.openFile(tFile, 2) |
|||
if fp.status() then return false |
|||
fp.writeByteArray(tByteArray) |
|||
fp.closeFile() |
|||
return true |
|||
end</syntaxhighlight> |
|||
<syntaxhighlight lang="lingo">data = getBytes("input.txt") |
|||
end</lang> |
|||
putBytes("output.txt", data)</syntaxhighlight> |
|||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">Section Header |
||
+ name := FILE_IO; |
+ name := FILE_IO; |
||
Line 993: | Line 2,693: | ||
}; |
}; |
||
}; |
}; |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
{{works with|UCB Logo}} |
{{works with|UCB Logo}} |
||
< |
<syntaxhighlight lang="logo">to copy :from :to |
||
openread :from |
openread :from |
||
openwrite :to |
openwrite :to |
||
Line 1,006: | Line 2,706: | ||
end |
end |
||
copy "input.txt "output.txt</ |
copy "input.txt "output.txt</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<syntaxhighlight lang="lua"> |
|||
<lang lua>io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))</lang> |
|||
inFile = io.open("input.txt", "r") |
|||
data = inFile:read("*all") -- may be abbreviated to "*a"; |
|||
-- other options are "*line", |
|||
-- or the number of characters to read. |
|||
inFile:close() |
|||
outFile = io.open("output.txt", "w") |
|||
outfile:write(data) |
|||
outfile:close() |
|||
-- Oneliner version: |
|||
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a")) |
|||
</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
|||
===Using Document Object=== |
|||
We can use Open for input/ Input$()/close, Open for Output/Print/close, but using a Document object is better, because Load.Doc can find the type of line breack and the coding, if it is UTF-8, UTG-16LE/BE and Ansi (we can provide another argument with specific way to open, or a Locale id for Ansi). When we save the document, we use the same format, so we preserve the coding and the line break type. |
|||
Open statement works for ANSI and using Wide for UTF-16LE only. |
|||
Here we use Edit to make Input.txt and edit some lines of text. Pressing Esc text saved to disk. Using Load.Doc we get the Input.txt, and we can display it using Report (which render text with word wrap, in M2000 console, using proportional text rendering), also if we have many lines there is a stop in each 3/4 of scrolling lines, to wait for a space bar or mouse click. |
|||
After a wait for a keypress Doc$ saved to Output.txt, and we open it in editor. |
|||
We can use Edit.Doc to edit Doc$, without save and then open for edit. |
|||
We can edit thousands of lines. Document is a double linked list. |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module FileInputOutput { |
|||
Edit "Input.txt" |
|||
Document Doc$ |
|||
Load.Doc Doc$, "Input.txt" |
|||
Report Doc$ |
|||
Print "Press a key:";Key$ |
|||
Save.Doc Doc$, "Output.txt" |
|||
Edit "Output.txt" |
|||
} |
|||
FileInputOutput |
|||
</syntaxhighlight> |
|||
===Using Buffer Object=== |
|||
A buffer expose real pointer (address), so here M(0) is the address of first byte, and Len(m) is the size of buffer in bytes. This buffer is not for code, but for data (no execution allowed). |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Using_Buffer { |
|||
M=buffer("Input.txt") |
|||
Print Len(m) |
|||
Open "Output1.txt" For Wide Output as #F |
|||
Print #F, Eval$(M); |
|||
Close #F |
|||
Edit "Output1.txt" |
|||
z=Filelen("Output1.txt") |
|||
Print z |
|||
Open "OutputAscii.txt" For Output as #F |
|||
Print #F, Eval$(M); |
|||
Close #F |
|||
Print Filelen("OutputAscii.txt")=z/2 |
|||
Edit "OutputAscii.txt" |
|||
} |
|||
Using_Buffer |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple"> |
|||
inout:=proc(filename) |
|||
local f; |
|||
f:=FileTools[Text][ReadFile](filename); |
|||
FileTools[Text][WriteFile]("output.txt",f); |
|||
end proc; |
|||
</syntaxhighlight> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">SetDirectory@NotebookDirectory[]; |
|||
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ]; |
|||
CopyFile["input.txt", "output.txt"]</syntaxhighlight> |
|||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">inFile = openFile "input.txt" |
||
outFile = createFile "output.txt" |
outFile = createFile "output.txt" |
||
while not EOF inFile do |
while not EOF inFile do |
||
Line 1,018: | Line 2,793: | ||
) |
) |
||
close inFile |
close inFile |
||
close outFile</ |
close outFile</syntaxhighlight> |
||
=={{header| |
=={{header|Mercury}}== |
||
<syntaxhighlight lang="mercury">:- module file_io. |
|||
<lang Mathematica>SetDirectory@NotebookDirectory[]; |
|||
:- interface. |
|||
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ]; |
|||
CopyFile["input.txt", "output.txt"]</lang> |
|||
:- import_module io. |
|||
:- pred main(io::di, io::uo) is det. |
|||
:- implementation. |
|||
main(!IO) :- |
|||
io.open_input("input.txt", InputRes, !IO), |
|||
( |
|||
InputRes = ok(Input), |
|||
io.read_file_as_string(Input, ReadRes, !IO), |
|||
( |
|||
ReadRes = ok(Contents), |
|||
io.close_input(Input, !IO), |
|||
io.open_output("output.txt", OutputRes, !IO), |
|||
( |
|||
OutputRes = ok(Output), |
|||
io.write_string(Output, Contents, !IO), |
|||
io.close_output(Output, !IO) |
|||
; |
|||
OutputRes = error(OutputError), |
|||
print_io_error(OutputError, !IO) |
|||
) |
|||
; |
|||
ReadRes = error(_, ReadError), |
|||
print_io_error(ReadError, !IO) |
|||
) |
|||
; |
|||
InputRes = error(InputError), |
|||
print_io_error(InputError, !IO) |
|||
). |
|||
:- pred print_io_error(io.error::in, io::di, io::uo) is det. |
|||
print_io_error(Error, !IO) :- |
|||
io.stderr_stream(Stderr, !IO), |
|||
io.write_string(Stderr, io.error_message(Error), !IO), |
|||
io.set_exit_status(1, !IO).</syntaxhighlight> |
|||
=={{header|mIRC Scripting Language}}== |
=={{header|mIRC Scripting Language}}== |
||
{{works with|mIRC}} |
{{works with|mIRC}} |
||
< |
<syntaxhighlight lang="mirc">alias Write2FileAndReadIt { |
||
.write myfilename.txt Goodbye Mike! |
.write myfilename.txt Goodbye Mike! |
||
.echo -a Myfilename.txt contains: $read(myfilename.txt,1) |
.echo -a Myfilename.txt contains: $read(myfilename.txt,1) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Modula-3}}== |
|||
<syntaxhighlight lang="modula3">MODULE FileIO EXPORTS Main; |
|||
IMPORT IO, Rd, Wr; |
|||
<*FATAL ANY*> |
|||
VAR |
|||
infile: Rd.T; |
|||
outfile: Wr.T; |
|||
txt: TEXT; |
|||
BEGIN |
|||
infile := IO.OpenRead("input.txt"); |
|||
outfile := IO.OpenWrite("output.txt"); |
|||
txt := Rd.GetText(infile, LAST(CARDINAL)); |
|||
Wr.PutText(outfile, txt); |
|||
Rd.Close(infile); |
|||
Wr.Close(outfile); |
|||
END FileIO.</syntaxhighlight> |
|||
The code <code><*FATAL ANY*></code> is a pragma that tells the program to die if any exceptions (such as read/write errors) occur. |
|||
=={{header|Nanoquery}}== |
|||
{{trans|Ursa}} |
|||
<syntaxhighlight lang="nanoquery">import Nanoquery.IO |
|||
input = new(File, "input.txt") |
|||
output = new(File) |
|||
output.create("output.txt") |
|||
output.open("output.txt") |
|||
contents = input.readAll() |
|||
output.write(contents)</syntaxhighlight> |
|||
=={{header|NetRexx}}== |
|||
{{works with|Java|7}} |
|||
Takes advantage of some of the new path and file handling features of [[Java|Java's]] <tt>java.nio</tt> library. |
|||
<syntaxhighlight lang="netrexx">/* NetRexx */ |
|||
options replace format comments java crossref symbols nobinary |
|||
import java.nio. |
|||
parse arg infileName outfileName . |
|||
if infileName = '' | infileName.length = 0 then infileName = 'data/input.txt' |
|||
if outfileName = '' | outfileName.length = 0 then outfileName = 'data/output.txt' |
|||
binaryCopy(infileName, outfileName) |
|||
return |
|||
method binaryCopy(infileName, outfileName) public static |
|||
do |
|||
infile = Paths.get('.', [String infileName]) |
|||
outfile = Paths.get('.', [String outfileName]) |
|||
fileOctets = Files.readAllBytes(infile) |
|||
Files.write(outfile, fileOctets, [StandardOpenOption.WRITE, StandardOpenOption.CREATE]) |
|||
catch ioex = IOException |
|||
ioex.printStackTrace() |
|||
end |
|||
return |
|||
</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
Copying the file directly (without buffer): |
|||
<syntaxhighlight lang="nim">import os |
|||
copyfile("input.txt", "output.txt")</syntaxhighlight> |
|||
Buffer for the entire file: |
|||
<syntaxhighlight lang="nim">let x = readFile("input.txt") |
|||
writeFile("output.txt", x)</syntaxhighlight> |
|||
Line by line: |
|||
<syntaxhighlight lang="nim">var |
|||
i = open("input.txt") |
|||
o = open("output.txt", fmWrite) |
|||
for line in i.lines: |
|||
o.writeLine(line) |
|||
i.close() |
|||
o.close()</syntaxhighlight> |
|||
With a fixed sized buffer: |
|||
<syntaxhighlight lang="nim">const size = 4096 |
|||
var |
|||
i = open("input.txt") |
|||
o = open("output.txt", fmWrite) |
|||
buf: array[size, char] |
|||
while i.readBuffer(buf.addr, size) > 0: |
|||
discard o.writeBuffer(buf.addr, size) |
|||
i.close() |
|||
o.close()</syntaxhighlight> |
|||
Using memory mapping: |
|||
<syntaxhighlight lang="nim">import memfiles |
|||
var |
|||
i = memfiles.open("input.txt") |
|||
o = system.open("output.txt", fmWrite) |
|||
var written = o.writeBuffer(i.mem, i.size) |
|||
assert(written == i.size) |
|||
i.close() |
|||
o.close()</syntaxhighlight> |
|||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
let text = open "input.txt" |
|||
$text | save "output.txt" |
|||
</syntaxhighlight> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use IO; |
||
bundle Default { |
bundle Default { |
||
Line 1,053: | Line 2,986: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Object Pascal}}== |
|||
For procedural code see the [[File_IO#Delphi | Delphi]] code, which is perfectly fine in ObjectPascal. |
|||
For a more object oriented style one can use a TFilestream: |
|||
<syntaxhighlight lang="pascal">uses |
|||
classes; |
|||
begin |
|||
with TFileStream.Create('input.txt', fmOpenRead) do |
|||
try |
|||
SaveToFile('output.txt'); |
|||
finally |
|||
Free; |
|||
end; |
|||
end;</syntaxhighlight> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
{{works with|Cocoa}} |
|||
For copying files, using <code>NSFileManager</code> is preferred: |
|||
{{works with|GNUstep}} |
|||
<syntaxhighlight lang="objc">[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];</syntaxhighlight> |
|||
If you want to do it manually: |
|||
Read the contents of input.txt and place it in output.txt, creating a file if needed: |
|||
< |
<syntaxhighlight lang="objc">NSData *data = [NSData dataWithContentsOfFile:@"input.txt"]; |
||
[data writeToFile:@"output.txt" atomically:YES];</ |
[data writeToFile:@"output.txt" atomically:YES];</syntaxhighlight> |
||
Displayed without error checking to make it more clear. In real code you will need to add lot of error checking code, and maybe use <tt>dataWithContentsOfFile:error:</tt> if you want to get error information on failure. However, this code will mostly work correctly even if input does not exist or is not accessible. <tt>dataWithContentsOfFile:</tt> will return nil, and sending nil the message <tt>writeTofile:atomically:</tt> does nothing :-) |
Displayed without error checking to make it more clear. In real code you will need to add lot of error checking code, and maybe use <tt>dataWithContentsOfFile:error:</tt> if you want to get error information on failure. However, this code will mostly work correctly even if input does not exist or is not accessible. <tt>dataWithContentsOfFile:</tt> will return nil, and sending nil the message <tt>writeTofile:atomically:</tt> does nothing :-) |
||
Line 1,072: | Line 3,022: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
By line: |
By line: |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let ic = open_in "input.txt" in |
let ic = open_in "input.txt" in |
||
let oc = open_out "output.txt" in |
let oc = open_out "output.txt" in |
||
Line 1,084: | Line 3,034: | ||
close_in ic; |
close_in ic; |
||
close_out oc; |
close_out oc; |
||
;;</ |
;;</syntaxhighlight> |
||
By character: |
By character: |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let ic = open_in "input.txt" in |
let ic = open_in "input.txt" in |
||
let oc = open_out "output.txt" in |
let oc = open_out "output.txt" in |
||
Line 1,098: | Line 3,048: | ||
close_in ic; |
close_in ic; |
||
close_out oc; |
close_out oc; |
||
;;</ |
;;</syntaxhighlight> |
||
(Notice that ic and oc, of type ''in_channel'' and ''out_channel'', are buffered) |
(Notice that ic and oc, of type ''in_channel'' and ''out_channel'', are buffered) |
||
=={{header|Octave}}== |
|||
<syntaxhighlight lang="octave"> |
|||
in = fopen("input.txt", "r", "native"); |
|||
out = fopen("output.txt", "w","native"); |
|||
if (in == -1) |
|||
disp("Error opening input.txt for reading."); |
|||
else |
|||
if (out == -1) |
|||
disp("Error opening output.txt for writing."); |
|||
else |
|||
while (1) |
|||
[val,count]=fread(in,1,"uchar",0,"native"); |
|||
if (count > 0) |
|||
count=fwrite(out,val,"uchar",0,"native"); |
|||
if (count == 0) |
|||
disp("Error writing to output.txt."); |
|||
end |
|||
else |
|||
break; |
|||
end |
|||
endwhile |
|||
end |
|||
end |
|||
if (in != -1) |
|||
fclose(in); |
|||
end |
|||
if (out != -1) |
|||
fclose(out); |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:os" |
|||
main :: proc() { |
|||
data, ok := os.read_entire_file("input.txt") |
|||
defer delete(data) |
|||
ok = os.write_entire_file("output.txt", data) |
|||
}</syntaxhighlight> |
|||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">: fcopy(in, out) |
|||
| f g | |
|||
File newMode(in, File.BINARY) dup open(File.READ) ->f |
|||
File newMode(out, File.BINARY) dup open(File.WRITE) ->g |
|||
while(f >> dup notNull) [ g addChar ] drop |
|||
f close g close ;</syntaxhighlight> |
|||
Usage : |
|||
<syntaxhighlight lang="oforth">fcopy("input.txt", "output.txt")</syntaxhighlight> |
|||
=={{header|OpenEdge/Progress}}== |
|||
<syntaxhighlight lang="progress (openedge abl)">COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".</syntaxhighlight> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
class TextFile from Open.file Open.text end |
class TextFile from Open.file Open.text end |
||
Line 1,119: | Line 3,129: | ||
{CopyAll In Out} |
{CopyAll In Out} |
||
{Out close} |
{Out close} |
||
{In close}</ |
{In close}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
|||
<syntaxhighlight lang="parigp">f=read("filename.in"); |
|||
write("filename.out", f);</syntaxhighlight> |
|||
=={{header|Pascal}}== |
|||
The [http://wiki.freepascal.org/File_Handling_In_Pascal | FreePascal wiki] gives a detailed description. |
|||
For procedureal code see the [[File_IO#Delphi | Delphi]] examples. The [[File_IO#Object_Pascal | ObjectPascal]] example is more OO coding style. |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
{{works with|Perl|5.8.8}} |
{{works with|Perl|5.8.8}} |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/perl |
||
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!"; |
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!"; |
||
Line 1,141: | Line 3,159: | ||
close $fh_in; |
close $fh_in; |
||
close $fh_out;</ |
close $fh_out;</syntaxhighlight> |
||
Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples. |
Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples. |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
whole file as a single string (safe on small binary files) |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)</span> |
|||
<span style="color: #004080;">string</span> <span style="color: #000000;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">)</span> |
|||
<span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"output.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"wb"<span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">,<span style="color: #000000;">txt<span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">fn<span style="color: #0000FF;">) |
|||
<!--</syntaxhighlight>--> |
|||
line-by-line (text files only) |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #004080;">integer</span> <span style="color: #000000;">infn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"r"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
|||
<span style="color: #000000;">outfn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"output.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"w"<span style="color: #0000FF;">)</span> |
|||
<span style="color: #004080;">object</span> <span style="color: #000000;">line</span> |
|||
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets<span style="color: #0000FF;">(<span style="color: #000000;">infn<span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #004080;">atom<span style="color: #0000FF;">(<span style="color: #000000;">line<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">outfn<span style="color: #0000FF;">,<span style="color: #000000;">line<span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">infn<span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfn<span style="color: #0000FF;">) |
|||
<!--</syntaxhighlight>--> |
|||
byte-by-byte (safe on binary files) |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #004080;">integer</span> <span style="color: #004080;">byte<span style="color: #0000FF;">,</span> |
|||
<span style="color: #000000;">infd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"input.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"rb"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
|||
<span style="color: #000000;">outfd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open<span style="color: #0000FF;">(<span style="color: #008000;">"output.txt"<span style="color: #0000FF;">,<span style="color: #008000;">"wb"<span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #004080;">byte</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getc<span style="color: #0000FF;">(<span style="color: #000000;">infd<span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #004080;">byte<span style="color: #0000FF;">=<span style="color: #0000FF;">-<span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">outfd<span style="color: #0000FF;">,<span style="color: #004080;">byte<span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">infd<span style="color: #0000FF;">)</span> |
|||
<span style="color: #7060A8;">close<span style="color: #0000FF;">(<span style="color: #000000;">outfd<span style="color: #0000FF;">) |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
<lang perl6>my $in = open "input.txt"; |
|||
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/File_input/output |
|||
my $out = open "output.txt", :w; |
|||
by Galileo, 10/2022 #/ |
|||
for $in.lines -> $line { |
|||
$out.say($line); |
|||
}</lang> |
|||
def eof? dup -1 != enddef |
|||
or, using the new slurp operator: |
|||
"input.txt" "r" fopen |
|||
<lang perl6>(open "output.txt", :w).print(slurp "input.txt")</lang> |
|||
"output.txt" "w" fopen |
|||
over fgets |
|||
eof? while |
|||
over fputs |
|||
over fgets |
|||
eof? endwhile |
|||
drop fclose fclose</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|4}} |
{{works with|PHP|4}} |
||
< |
<syntaxhighlight lang="php"><?php |
||
if (!$in = fopen('input.txt', 'r')) { |
if (!$in = fopen('input.txt', 'r')) { |
||
Line 1,177: | Line 3,236: | ||
fclose($out); |
fclose($out); |
||
fclose($in); |
fclose($in); |
||
?></ |
?></syntaxhighlight> |
||
{{works with|PHP|5}} |
{{works with|PHP|5}} |
||
< |
<syntaxhighlight lang="php"><?php |
||
if ($contents = file_get_contents('input.txt')) { |
if ($contents = file_get_contents('input.txt')) { |
||
if (!file_put_contents('output.txt', $contents)) { |
if (!file_put_contents('output.txt', $contents)) { |
||
Line 1,188: | Line 3,247: | ||
echo('Could not open input file.'); |
echo('Could not open input file.'); |
||
} |
} |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
===Using a variable=== |
|||
<lang PicoLisp>(in "input.txt" |
|||
<syntaxhighlight lang="picolisp">(let V (in "input.txt" (till)) |
|||
(out "output.txt" (prin V)) )</syntaxhighlight> |
|||
===Skipping intermediate variable=== |
|||
<syntaxhighlight lang="picolisp">(in "input.txt" |
|||
(out "output.txt" |
(out "output.txt" |
||
(echo) ) )</ |
(echo) ) )</syntaxhighlight> |
||
=={{header|Pike}}== |
|||
===Line by line=== |
|||
<syntaxhighlight lang="pike"> |
|||
object lines = Stdio.File("input.txt")->line_iterator(); |
|||
object out = Stdio.File("output.txt", "cw"); |
|||
foreach(lines; int line_number; string line) |
|||
out->write(line + "\n"); |
|||
</syntaxhighlight> |
|||
Note that "\r" will be passed on like any other character. If line_iterator is called with the argument 1 it will however run in trim mode, and all "\r"s will be discarded. |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pli"> |
|||
<lang PL/I> |
|||
declare in file, out file; |
declare in file, out file; |
||
open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input; |
open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input; |
||
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100) output; |
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output; |
||
do forever; |
do forever; |
||
get file (in) edit (line) (L); |
get file (in) edit (line) (L); |
||
put file (out) edit (line) (A); |
put file (out) edit (line) (A); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 1,211: | Line 3,284: | ||
Char by char copy: |
Char by char copy: |
||
< |
<syntaxhighlight lang="pop11">lvars i_stream = discin('input.txt'); |
||
lvars o_stream = discout('output.txt'); |
lvars o_stream = discout('output.txt'); |
||
lvars c; |
lvars c; |
||
while (i_stream() ->> c) /= termin do |
while (i_stream() ->> c) /= termin do |
||
o_stream(c); |
o_stream(c); |
||
endwhile;</ |
endwhile;</syntaxhighlight> |
||
Low level block copy: |
Low level block copy: |
||
< |
<syntaxhighlight lang="pop11">lvars i_file = sysopen('input.txt', 0, true); |
||
lvars o_file = syscreate('output.txt', 1, true); |
lvars o_file = syscreate('output.txt', 1, true); |
||
lvars buff = inits(4096); |
lvars buff = inits(4096); |
||
Line 1,226: | Line 3,299: | ||
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do |
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do |
||
syswrite(o_file, buff, i); |
syswrite(o_file, buff, i); |
||
endwhile;</ |
endwhile;</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
Line 1,232: | Line 3,305: | ||
Read the input file then pipe it's contents to output file. |
Read the input file then pipe it's contents to output file. |
||
Assumes that the files are in the same folder that the script is executing in. |
Assumes that the files are in the same folder that the script is executing in. |
||
< |
<syntaxhighlight lang="powershell">Get-Content $PWD\input.txt | Out-File $PWD\output.txt</syntaxhighlight> |
||
Using an alternate cmdlet to write the file |
Using an alternate cmdlet to write the file |
||
< |
<syntaxhighlight lang="powershell">Get-Content $PWD\input.txt | Set-Content $PWD\output.txt</syntaxhighlight> |
||
=={{header|PureBasic}}== |
|||
Basic file copy |
|||
<lang PureBasic>CopyFile("input.txt","output.txt")</lang> |
|||
Line by line |
|||
<lang PureBasic>in = ReadFile(#PB_Any,"input.txt") |
|||
If in |
|||
out = CreateFile(#PB_Any,"output.txt") |
|||
If out |
|||
Define MyLine$ |
|||
While Not Eof(in) |
|||
MyLine$ = ReadString(in) |
|||
WriteString(out,MyLine$) |
|||
Wend |
|||
CloseFile(out) |
|||
EndIf |
|||
CloseFile(in) |
|||
EndIf</lang> |
|||
Reading & writing the complete file in one pass |
|||
<lang PureBasic>If ReadFile(0,"input.txt") |
|||
Define MyLine$, *Buffer, length |
|||
length=FileSize("input.txt") |
|||
*Buffer = AllocateMemory(length) |
|||
If *Buffer |
|||
If OpenFile(1,"output.txt") |
|||
ReadData(0, *Buffer, length) |
|||
WriteData(1, *Buffer, length) |
|||
CloseFile(1) |
|||
EndIf |
|||
FreeMemory(*Buffer) |
|||
EndIf |
|||
CloseFile(0) |
|||
EndIf</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures that failure to open files raises appropriate exceptions, a restricted buffer is used to copy the files using binary mode, and any used file descriptors are always closed). |
The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures that failure to open files raises appropriate exceptions, a restricted buffer is used to copy the files using binary mode, and any used file descriptors are always closed). |
||
< |
<syntaxhighlight lang="python">import shutil |
||
shutil.copyfile('input.txt', 'output.txt')</ |
shutil.copyfile('input.txt', 'output.txt')</syntaxhighlight> |
||
However the following example shows how one would do file I/O of other sorts: |
However the following example shows how one would do file I/O of other sorts: |
||
< |
<syntaxhighlight lang="python">infile = open('input.txt', 'r') |
||
outfile = open('output.txt', 'w') |
outfile = open('output.txt', 'w') |
||
for line in infile: |
for line in infile: |
||
outfile.write(line) |
outfile.write(line) |
||
outfile.close() |
outfile.close() |
||
infile.close()</ |
infile.close()</syntaxhighlight> |
||
This does no error checking. A more robust program would wrap each open with exception handling blocks: |
This does no error checking. A more robust program would wrap each open with exception handling blocks: |
||
< |
<syntaxhighlight lang="python">import sys |
||
try: |
try: |
||
infile = open('input.txt', 'r') |
infile = open('input.txt', 'r') |
||
Line 1,314: | Line 3,346: | ||
finally: |
finally: |
||
infile.close() |
infile.close() |
||
outfile.close()</ |
outfile.close()</syntaxhighlight> |
||
In Python 2.6 (or 2.5 if we use ''from __future__ import with_statement'') we can more simply write: |
In Python 2.6 (or 2.5 if we use ''from __future__ import with_statement'') we can more simply write: |
||
< |
<syntaxhighlight lang="python">import sys |
||
try: |
try: |
||
with open('input.txt') as infile: |
with open('input.txt') as infile: |
||
Line 1,326: | Line 3,358: | ||
except IOError: |
except IOError: |
||
print >> sys.stderr, "Some I/O Error occurred" |
print >> sys.stderr, "Some I/O Error occurred" |
||
sys.exit(1)</ |
sys.exit(1)</syntaxhighlight> |
||
The files will automatically be closed on exit of their ''with:'' blocks. (Thus even if an I/O error occurred while reading the middle of the input file we are assured that the ''.close()'' method will have been called on each of the two files. |
The files will automatically be closed on exit of their ''with:'' blocks. (Thus even if an I/O error occurred while reading the middle of the input file we are assured that the ''.close()'' method will have been called on each of the two files. |
||
=={{header|Quackery}}== |
|||
Assuming that <code>input.txt</code> exists beforehand, and <code>output.txt</code> does not (so we can safely <code>drop</code> the success flag that file handling words return), and that we want both files to exist afterwards. |
|||
Quackery does not have variables, so instead we will move the file text to and from the ancillary stack <code>temp</code>, leaving a copy on the top of <code>temp</code>. |
|||
<syntaxhighlight lang="quackery"> $ "input.txt" sharefile drop |
|||
temp put |
|||
temp share |
|||
$ "output.txt" putfile drop |
|||
</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end") |
If files are textual we can use <tt>readLines</tt> ("-1" means "read until the end") |
||
< |
<syntaxhighlight lang="rsplus">src <- file("input.txt", "r") |
||
dest <- file("output.txt", "w") |
dest <- file("output.txt", "w") |
||
fc <- readLines(src, -1) |
fc <- readLines(src, -1) |
||
writeLines(fc, dest) |
writeLines(fc, dest) |
||
close(src); close(dest)</ |
close(src); close(dest)</syntaxhighlight> |
||
If the files are not textual but "generic": |
If the files are not textual but "generic": |
||
< |
<syntaxhighlight lang="rsplus">src <- file("input.txt", "rb") |
||
dest <- file("output.txt", "wb") |
dest <- file("output.txt", "wb") |
||
Line 1,348: | Line 3,392: | ||
writeBin(v, dest) |
writeBin(v, dest) |
||
} |
} |
||
close(src); close(dest)</ |
close(src); close(dest)</syntaxhighlight> |
||
Another simpler way is to use <tt>file.copy</tt> |
Another simpler way is to use <tt>file.copy</tt> |
||
< |
<syntaxhighlight lang="rsplus">file.copy("input.txt", "output.txt", overwrite = FALSE)</syntaxhighlight> |
||
=={{header| |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket">#lang racket |
|||
(define file-content |
|||
(with-input-from-file "input.txt" |
|||
(lambda () |
|||
(let loop ((lst null)) |
|||
(define new (read-char)) |
|||
(if (eof-object? new) |
|||
(apply string lst) |
|||
(loop (append lst (list new)))))))) |
|||
(with-output-to-file "output.txt" |
|||
File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams. |
|||
(lambda () |
|||
(write file-content)))</syntaxhighlight> |
|||
=={{header|Raku}}== |
|||
The first version copies text line by line, as in the ''BASIC'' example. |
|||
(formerly Perl 6) |
|||
If it is okay to have a temporary copy of the entire file in memory: |
|||
<lang rapidq>$INCLUDE "rapidq.inc" |
|||
{{works with|Rakudo|2016.07}} |
|||
DIM File1 AS QFileStream |
|||
<syntaxhighlight lang="raku" line>spurt "output.txt", slurp "input.txt";</syntaxhighlight> |
|||
DIM File2 AS QFileStream |
|||
Otherwise, copying line-by line: |
|||
File1.Open("input.txt", fmOpenRead) |
|||
File2.Open("output.txt", fmCreate) |
|||
{{works with|Rakudo|2015.12}} |
|||
WHILE NOT File1.EOF |
|||
<syntaxhighlight lang="raku" line>my $in = open "input.txt"; |
|||
data$ = File1.ReadLine |
|||
my $out = open "output.txt", :w; |
|||
File2.WriteLine(data$) |
|||
for $in.lines -> $line { |
|||
WEND |
|||
$out.say: $line; |
|||
} |
|||
File1.Close |
|||
$in.close; |
|||
File2.Close</lang> |
|||
$out.close;</syntaxhighlight> |
|||
When just copying data, the code can be simplified by using the CopyFrom method.<br /> |
|||
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.) |
|||
<lang rapidq>$INCLUDE "rapidq.inc" |
|||
DIM File1 AS QFileStream |
|||
DIM File2 AS QFileStream |
|||
File1.Open("input.txt", fmOpenRead) |
|||
File2.Open("output.txt", fmCreate) |
|||
File2.CopyFrom(File1, 0) |
|||
File1.Close |
|||
File2.Close</lang> |
|||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">'input.txt' read 'output.txt' write</syntaxhighlight> |
||
=={{header|REALbasic}}== |
|||
<lang realbasic> |
|||
Sub WriteToFile(Extends input As FolderItem, output As FolderItem) |
|||
Dim tis As TextInputStream |
|||
Dim tos As TextOutputStream |
|||
tis = tis.Open(input) |
|||
tos = tos.Create(output) |
|||
While Not tis.EOF |
|||
tos.WriteLine(tis.ReadLine) |
|||
Wend |
|||
tis.Close |
|||
tos.Close |
|||
End Sub |
|||
</lang> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">write %output.txt read %input.txt |
||
; No line translations: |
; No line translations: |
||
Line 1,417: | Line 3,443: | ||
; Save a web page: |
; Save a web page: |
||
write/binary %output.html read http://rosettacode.org |
write/binary %output.html read http://rosettacode.org |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Red}}== |
|||
<syntaxhighlight lang="red"> |
|||
file: read %input.txt |
|||
write %output.txt file</syntaxhighlight> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">with files' |
||
here dup "input.txt" slurp "output.txt" spew</ |
here dup "input.txt" slurp "output.txt" spew</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
In REXX, filename association is used rather than numeric stream numbers and explicit file opening is not required. |
|||
In rexx, filename association is used rather than numeric stream numbers and explicit file opening is not required. |
|||
===version 1=== |
===version 1=== |
||
The two ''optional'' REXX statements are only needed if there is another REXX program in the invocation chain |
|||
<lang rexx> |
|||
<br>(which may have invoked this program) that already has one of the input and/or output files open. |
|||
The two ''best programming practice'' REXX statements are only needed if there is another calling program in the invocation chain |
|||
ifid='input.txt' /*name of the input file. */ |
|||
<br>(which may want to (re-)use the two files just used. |
|||
ofid='output.txt /*name of the output file. */ |
|||
<syntaxhighlight lang="rexx">/*REXX program reads a file and copies the contents into an output file (on a line by line basis).*/ |
|||
iFID = 'input.txt' /*the name of the input file. */ |
|||
oFID = 'output.txt' /* " " " " output " */ |
|||
call lineout iFID,,1 /*insure the input starts at line one.*/ /* ◄■■■■■■ optional.*/ |
|||
call lineout oFID,,1 /* " " output " " " " */ /* ◄■■■■■■ optional.*/ |
|||
do while lines(iFID)\==0; $=linein(iFID) /*read records from input 'til finished*/ |
|||
call lineout oFID, $ /*write the record just read ──► output*/ |
|||
end /*while*/ /*stick a fork in it, we're all done. */ |
|||
call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/ |
|||
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/</syntaxhighlight> |
|||
do while lines(ifid)\==0 /*read until finished. */ |
|||
y=linein(ifid) /* read a record from input. */ |
|||
call lineout ofid,y /*write a record to output.nt. */ |
|||
end |
|||
</lang> |
|||
===version 2=== |
===version 2=== |
||
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory). |
|||
<lang rexx> |
|||
/*REXX program to read a file and |
<syntaxhighlight lang="rexx">/*REXX program to read a file and write contents to an output file***** |
||
* 03.09.2012 Walter Pachl (without erase string would be appended) |
|||
**********************************************************************/ |
|||
ifid='input.txt' /*name of the input file. */ |
|||
ofid='output.txt' /*name of the output file. */ |
|||
'erase' ofid /* avoid appending */ |
|||
s=charin(ifid,,1000000) /* read the input file */ |
|||
Call charout ofid,s /* write to output file */</syntaxhighlight> |
|||
=={{header|Ring}}== |
|||
ifid='input.txt' /*name of the input file. */ |
|||
<syntaxhighlight lang="ring"> |
|||
ofid='output.txt /*name of the output file. */ |
|||
fn1 = "ReadMe.txt" |
|||
fn2 = "ReadMe2.txt" |
|||
fp = fopen(fn1,"r") |
|||
do while lines(ifid)\==0 /*read until finished. */ |
|||
str = fread(fp, getFileSize(fp)) |
|||
call lineout ofid,linein(ifid) /*read & write in one statement. */ |
|||
fclose(fp) |
|||
end |
|||
</lang> |
|||
fp = fopen(fn2,"w") |
|||
fwrite(fp, str) |
|||
fclose(fp) |
|||
see "OK" + nl |
|||
func getFileSize fp |
|||
c_filestart = 0 |
|||
c_fileend = 2 |
|||
fseek(fp,0,c_fileend) |
|||
nfilesize = ftell(fp) |
|||
fseek(fp,0,c_filestart) |
|||
return nfilesize |
|||
</syntaxhighlight> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
In general, open both files in binary mode. |
|||
{{works with|Ruby|1.8.4}} |
|||
<lang ruby> |
|||
File.open(' |
<syntaxhighlight lang="ruby">str = File.open('input.txt', 'rb') {|f| f.read} |
||
File.open('output.txt', 'wb') {|f| f.write str}</syntaxhighlight> |
|||
file.write File.read 'input.txt' |
|||
If 'input.txt' is a text file, we may forget binary mode. If no pathname begins with a pipe '|', then we may use ''IO::read'' and ''Kernel#open''. (The pipe is a problem, because <code>IO.read('| uname')</code> or <code>open('| sh', 'w')</code> would open a subprocess and not a file.) |
|||
<syntaxhighlight lang="ruby"># Only if 'input.txt' is a text file! |
|||
# Only if pipe '|' is not first character of path! |
|||
str = IO.read('input.txt') |
|||
open('output.txt', 'w') {|f| f.write str}</syntaxhighlight> |
|||
To copy a file block by block, use FileUtils from the standard library. |
|||
<syntaxhighlight lang="ruby">require 'fileutils' |
|||
FileUtils.copy_file 'input.txt', 'output.txt'</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in |
|||
fileLen = LOF(#in) 'Length Of File |
|||
fileData$ = input$(#in, fileLen) 'read entire file |
|||
close #in |
|||
open "output.txt" for output as #out |
|||
print #out, fileData$ 'write entire fie |
|||
close #out |
|||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or directly with no intermediate fileData$ |
|||
OR |
|||
{{works with|Just BASIC}} |
|||
<lang ruby> |
|||
<syntaxhighlight lang="runbasic">open "input.txt" for input as #in |
|||
File.open('output.txt', 'w') { |file| file.write File.read 'input.txt' } |
|||
open "output.txt" for output as #out |
|||
</lang> |
|||
fileLen = LOF(#in) 'Length Of File |
|||
print #out, input$(#in, fileLen) 'entire file |
|||
close #in |
|||
close #out |
|||
</syntaxhighlight> |
|||
=={{header|Rust}}== |
|||
<syntaxhighlight lang="rust">fn main() { |
|||
let contents = std::fs::read("input.txt").expect("error reading input.txt"); |
|||
std::fs::write("output.txt", contents).expect("error writing output.txt"); |
|||
} |
|||
</syntaxhighlight> |
|||
The above program will panic with any sort of error. The following shows proper error handling: |
|||
<syntaxhighlight lang="rust">use std::fs::File; |
|||
use std::io::{self, Read, Write}; |
|||
use std::path::Path; |
|||
use std::{env, fmt, process}; |
|||
fn main() { |
|||
let files: Vec<_> = env::args_os().skip(1).take(2).collect(); |
|||
if files.len() != 2 { |
|||
exit_err("Both an input file and output file are required", 1); |
|||
} |
|||
copy(&files[0], &files[1]).unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1))); |
|||
} |
|||
fn copy<P: AsRef<Path>>(infile: P, outfile: P) -> io::Result<()> { |
|||
let mut vec = Vec::new(); |
|||
Ok(try!(File::open(infile) |
|||
.and_then(|mut i| i.read_to_end(&mut vec)) |
|||
.and_then(|_| File::create(outfile)) |
|||
.and_then(|mut o| o.write_all(&vec)))) |
|||
} |
|||
fn exit_err<T: fmt::Display>(msg: T, code: i32) -> ! { |
|||
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout"); |
|||
process::exit(code); |
|||
}</syntaxhighlight> |
|||
=={{header|S-BASIC}}== |
|||
Surprisingly, S-BASIC has no EOF function, so we have to rely on error trapping to signal end of file. S-BASIC stores its error codes at 103H, and we can position a base-located variable there to retrieve it. The result is something of a kludge, but it works. Other S-BASIC preculiarities are explained by the comments. |
|||
<syntaxhighlight lang="BASIC"> |
|||
comment |
|||
Preserve file channel #0 (the console) while declaring channels |
|||
#2 and #3 as sequential-access ASCII files. |
|||
end |
|||
files d, sa, sa |
|||
var s = string:255 |
|||
based errcode = integer |
|||
base errcode at 103H |
|||
comment |
|||
CP/M expects upper case file names, but S-BASIC does not |
|||
automatically convert file name arguments to upper case, so we |
|||
have to do that ourself. |
|||
end |
|||
create "OUTPUT.TXT" |
|||
open #1,"INPUT.TXT" |
|||
open #2,"OUTPUT.TXT" |
|||
comment |
|||
S-BASIC allows alphanumeric line "numbers" (which are treated simply |
|||
as labels) as the target of GOTO and GOSUB statements, but the first |
|||
character must be a digit |
|||
end |
|||
on error goto 9done |
|||
rem - runtime error code 15 signals read past end of file |
|||
while errcode <> 15 do |
|||
begin |
|||
input3 #1; s |
|||
print #2; s |
|||
end |
|||
9done |
|||
close #1 |
|||
close #2 |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{ |
{{libheader|Scala}} |
||
<syntaxhighlight lang="scala">import java.io.{ FileNotFoundException, PrintWriter } |
|||
object FileIO extends App { |
|||
Line by line copy |
|||
try { |
|||
<lang scala> |
|||
val |
val MyFileTxtTarget = new PrintWriter("output.txt") |
||
val dest = new java.io.PrintWriter(new java.io.File("output.txt")) |
|||
scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println) |
|||
// Read from source line by line and for each line print to file |
|||
MyFileTxtTarget.close() |
|||
src.getLines().foreach(dest.println(_)) |
|||
} catch { |
|||
dest.close() |
|||
case e: FileNotFoundException => println(e.getLocalizedMessage()) |
|||
src.close() |
|||
case e: Throwable => { |
|||
</lang> |
|||
println("Some other exception type:") |
|||
e.printStackTrace() |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
Character by character copy< |
Character by character copy<syntaxhighlight lang="scheme">; Open ports for the input and output files |
||
(define in-file (open-input-file "input.txt")) |
(define in-file (open-input-file "input.txt")) |
||
(define out-file (open-output-file "output.txt")) |
(define out-file (open-output-file "output.txt")) |
||
Line 1,490: | Line 3,662: | ||
(close-input-port in-file) |
(close-input-port in-file) |
||
(close-output-port out-file) |
(close-output-port out-file) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Seed7}}== |
|||
The library [http://seed7.sourceforge.net/libraries/osfiles.htm osfiles.s7i] contains the |
|||
function [http://seed7.sourceforge.net/libraries/osfiles.htm#copyFile%28in_string,in_string%29 copyFile] which |
|||
can be used to copy a source file to a destination. |
|||
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
|||
include "osfiles.s7i"; |
|||
const proc: main is func |
|||
begin |
|||
copyFile("input.txt", "output.txt"); |
|||
end func;</syntaxhighlight> |
|||
=={{header|SenseTalk}}== |
|||
Reading the file all at once: |
|||
<syntaxhighlight lang="sensetalk">put file "input.txt" into fileContents |
|||
put fileContents into file "output.txt"</syntaxhighlight> |
|||
Reading the file line by line: |
|||
<syntaxhighlight lang="sensetalk">put "input.txt" into inputFile |
|||
put "output.txt" into outputFile |
|||
open file inputFile |
|||
open file outputFile for writing |
|||
repeat forever |
|||
read from file inputFile until return |
|||
if it is empty then exit repeat |
|||
write it to file outputFile |
|||
end repeat |
|||
close file inputFile |
|||
close file outputFile</syntaxhighlight> |
|||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby">var in = %f'input.txt'.open_r; |
|||
var out = %f'output.txt'.open_w; |
|||
in.each { |line| |
|||
out.print(line); |
|||
};</syntaxhighlight> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in | |
||
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out | |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out | |
||
in >> out]]</ |
in >> out]]</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">| in out | |
||
in := FileStream open: 'input.txt' mode: FileStream read. |
in := FileStream open: 'input.txt' mode: FileStream read. |
||
out := FileStream open: 'output.txt' mode: FileStream write. |
out := FileStream open: 'output.txt' mode: FileStream write. |
||
Line 1,504: | Line 3,717: | ||
whileFalse: [ |
whileFalse: [ |
||
out nextPut: (in next) |
out nextPut: (in next) |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Snabel}}== |
|||
Reads the entire file into into a list of buffers before writing and returns number of bytes written. |
|||
<syntaxhighlight lang="snabel"> |
|||
let: q Bin list; |
|||
'input.txt' rfile read {{@q $1 push} when} for |
|||
@q 'output.txt' rwfile write |
|||
0 $1 &+ for |
|||
</syntaxhighlight> |
|||
Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written. |
|||
<syntaxhighlight lang="snabel"> |
|||
let: q Bin list; |
|||
let: wq @q fifo; |
|||
let: w 'output.txt' rwfile @wq $1 write; |
|||
'input.txt' rfile read 0 $1 {{ |
|||
$ @q $1 push |
|||
len + |
|||
@w &break _for |
|||
} when} for |
|||
@q +? {@w &_ for} when |
|||
</syntaxhighlight> |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4"> |
||
input(.input,5,,'input.txt') |
input(.input,5,,'input.txt') |
||
output(.output,6,,'output.txt') |
output(.output,6,,'output.txt') |
||
while output = input :s(while) |
while output = input :s(while) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "filecopy" ) |
|||
@( description, "The job is to create a file called 'output.txt', and place in it" ) |
|||
@( description, "the contents of the file 'input.txt'." ) |
|||
@( category, "tutorials" ) |
|||
@( author, "Ken O. Burtch" ) |
|||
@( see_also, "http://rosettacode.org/wiki/File_IO" ); |
|||
pragma software_model( nonstandard ); |
|||
pragma license( unrestricted ); |
|||
procedure filecopy is |
|||
begin |
|||
if not files.is_readable( "input.txt" ) then |
|||
put_line( standard_error, source_info.source_location & ": input file is not readable" ); |
|||
command_line.set_exit_status( 192 ); |
|||
return; |
|||
end if; |
|||
-- With standard shell commands |
|||
cp input.txt output.txt; |
|||
-- Using built-in capabilities |
|||
pragma restriction( no_external_commands ); |
|||
declare |
|||
inputfile : file_type; |
|||
outputfile : file_type; |
|||
begin |
|||
create( outputfile, out_file, "output.txt" ); |
|||
open( inputfile, in_file, "input.txt" ); |
|||
while not end_of_file( inputfile ) loop |
|||
put_line( outputfile, get_line( inputfile ) ); |
|||
end loop; |
|||
close( inputfile ) @ ( outputfile ); |
|||
end; |
|||
end filecopy;</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
===Reading the whole file at once as a string=== |
|||
{{works with|SML/NJ|110.59}} |
{{works with|SML/NJ|110.59}} |
||
{{works with|Poly/ML|5.9.1}} |
|||
<lang sml>fun copyFile (from, to) = |
|||
<syntaxhighlight lang="sml"> |
|||
(* string -> string -> bool *) |
|||
fun copyFile from to = |
|||
let |
let |
||
val instream = TextIO.openIn from |
val instream = TextIO.openIn from |
||
Line 1,525: | Line 3,809: | ||
in |
in |
||
true |
true |
||
end handle _ => false |
end handle _ => false</syntaxhighlight> |
||
===Binary mode using a buffer=== |
|||
{{works with|Poly/ML|5.9.1}} |
|||
{{works with|SML/NJ|110.99.4}} |
|||
<syntaxhighlight lang="sml"> |
|||
fun copyFile from to = |
|||
let |
|||
val instream = BinIO.openIn from |
|||
val outstream = BinIO.openOut to |
|||
fun aux () = |
|||
let |
|||
val buf = BinIO.inputN(instream, 1024) |
|||
in |
|||
if Word8Vector.length buf = 0 |
|||
then () |
|||
else (BinIO.output (outstream, buf); aux ()) |
|||
end |
|||
in |
|||
(aux (); BinIO.closeIn instream; BinIO.closeOut outstream) |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|Stata}}== |
|||
Stata has a [http://www.stata.com/help.cgi?copy copy] command. Here is a way to implement this by reading and writing line by line. |
|||
<syntaxhighlight lang="stata">program copyfile |
|||
file open fin using `1', read text |
|||
file open fout using `2', write text replace |
|||
file read fin line |
|||
while !r(eof) { |
|||
file write fout `"`line'"' _newline |
|||
file read fin line |
|||
} |
|||
file close fin |
|||
file close fout |
|||
end |
|||
copyfile input.txt output.txt</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{works with|tclsh}} |
{{works with|tclsh}} |
||
{{works with|eTcl}} |
{{works with|eTcl}} |
||
{{works with|wish}} |
{{works with|wish}} |
||
{{works with|tixwish}} |
{{works with|tixwish}} |
||
{{works with|tclkit}} |
|||
< |
<syntaxhighlight lang="tcl">set in [open "input.txt" r] |
||
set out [open "output.txt" w] |
set out [open "output.txt" w] |
||
# Obviously, arbitrary transformations could be added to the data at this point |
# Obviously, arbitrary transformations could be added to the data at this point |
||
puts -nonewline $out [read $in] |
puts -nonewline $out [read $in] |
||
close $in |
close $in |
||
close $out</ |
close $out</syntaxhighlight> |
||
For larger files, it is better to use the <tt>fcopy</tt> command, though in general this restricts what operations can be performed rather more (only encoding and end-of-line translations are possible |
For larger files, it is better to use the <tt>fcopy</tt> command, though in general this restricts what operations can be performed rather more (only encoding and end-of-line translations are possible — or more general byte-level transformations with the generic filter mechanism provided in Tcl 8.6 — none of which are shown here): |
||
< |
<syntaxhighlight lang="tcl">set in [open "input.txt" r] |
||
set out [open "output.txt" w] |
set out [open "output.txt" w] |
||
fcopy $in $out |
fcopy $in $out |
||
close $in |
close $in |
||
close $out</ |
close $out</syntaxhighlight> |
||
Or the minimal version if we don't need any processing of the data at all: |
Or the minimal version if we don't need any processing of the data at all: |
||
< |
<syntaxhighlight lang="tcl">file copy input.txt output.txt</syntaxhighlight> |
||
===Other key file I/O operations=== |
|||
;Writing a line to a file<nowiki>:</nowiki> |
|||
Other File I/O: |
|||
<syntaxhighlight lang="tcl">#open file for writing |
|||
<lang tcl>#open file for writing |
|||
set myfile [open "README.TXT" w] |
set myfile [open "README.TXT" w] |
||
#write something to the file |
#write something to the file |
||
puts $myfile "This is line 1, so hello world...." |
puts $myfile "This is line 1, so hello world...." |
||
#close the file |
#close the file |
||
close $myfile</ |
close $myfile</syntaxhighlight> |
||
;Reading a line from a file<nowiki>:</nowiki> |
|||
< |
<syntaxhighlight lang="tcl">#open file for reading |
||
set myfile [open "README.TXT" r] |
set myfile [open "README.TXT" r] |
||
#read something from the file |
#read something from the file |
||
Line 1,569: | Line 3,885: | ||
puts $mydata |
puts $mydata |
||
#close the file |
#close the file |
||
close $myfile</ |
close $myfile</syntaxhighlight> |
||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
This is one method, which works with any type of file: |
This is one method, which works with any type of file: |
||
< |
<syntaxhighlight lang="toka">( source dest -- ) |
||
{ |
{ |
||
value| source dest size buffer | |
value| source dest size buffer | |
||
Line 1,595: | Line 3,911: | ||
[ source file.close dest file.close ] is close-files |
[ source file.close dest file.close ] is close-files |
||
[ prepare [ read-source write-dest close-files ] ifTrue ] |
[ prepare [ read-source write-dest close-files ] ifTrue ] |
||
} is copy-file</ |
} is copy-file</syntaxhighlight> |
||
And a much simpler way for plain text files, making use of file.slurp: |
And a much simpler way for plain text files, making use of file.slurp: |
||
< |
<syntaxhighlight lang="toka">[ ( source dest -- ) |
||
swap file.slurp dup 0 <> |
swap file.slurp dup 0 <> |
||
[ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue |
[ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue |
||
] is copy-file</ |
] is copy-file</syntaxhighlight> |
||
And a test: |
And a test: |
||
< |
<syntaxhighlight lang="toka">" input.txt" " output.txt" copy-file</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
|||
<syntaxhighlight lang="tuscript"> |
|||
$$ MODE TUSCRIPT |
|||
ERROR/STOP CREATE ("input.txt", seq-o,-std-) |
|||
ERROR/STOP CREATE ("output.txt",seq-o,-std-) |
|||
FILE/ERASE "input.txt" = "Some irrelevant content" |
|||
path2input =FULLNAME(TUSTEP,"input.txt", -std-) |
|||
status=READ (path2input,contentinput) |
|||
path2output=FULLNAME(TUSTEP,"output.txt",-std-) |
|||
status=WRITE(path2output,contentinput) |
|||
</syntaxhighlight> |
|||
=={{header|TXR}}== |
|||
As a character string: |
|||
<syntaxhighlight lang="txrlisp">(let ((var (file-get-string "input.txt"))) |
|||
(file-put-string "output.txt" var))</syntaxhighlight> |
|||
As a list of lines: |
|||
<syntaxhighlight lang="txrlisp">(let ((var (file-get-lines "input.txt"))) |
|||
(file-put-lines "output.txt" var))</syntaxhighlight> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 1,614: | Line 3,956: | ||
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one. |
* Caveat: output.txt will end with a newline, whether or not input.txt ended with one. |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
while IFS= read -r a; do |
while IFS= read -r a; do |
||
printf '%s\n' "$a" |
printf '%s\n' "$a" |
||
done <input.txt >output.txt</ |
done <input.txt >output.txt</syntaxhighlight> |
||
Another way, using the 'cat' program |
Another way, using the 'cat' program |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
cat input.txt >output.txt</ |
cat input.txt >output.txt</syntaxhighlight> |
||
Yet another way, using the 'cp' utility |
Yet another way, using the 'cp' utility |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
cp input.txt output.txt</ |
cp input.txt output.txt</syntaxhighlight> |
||
=={{header|Ursa}}== |
|||
<syntaxhighlight lang="ursa">decl file input output |
|||
decl string contents |
|||
input.open "input.txt" |
|||
output.create "output.txt" |
|||
output.open "output.txt" |
|||
set contents (input.readall) |
|||
out contents output</syntaxhighlight> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 1,636: | Line 3,987: | ||
Returning a copy of the input file with a new name causes it to be |
Returning a copy of the input file with a new name causes it to be |
||
written as a new file. |
written as a new file. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#executable ('parameterized','') |
#executable ('parameterized','') |
||
fileio = ~command.files; &h.path.&h:= 'output.txt'!</ |
fileio = ~command.files; &h.path.&h:= 'output.txt'!</syntaxhighlight> |
||
=={{header| |
=={{header|Uxntal}}== |
||
<syntaxhighlight lang="Uxntal">|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 |
|||
one liner (-2 for system default encoding) |
|||
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 |
|||
<lang vb>CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll</lang> |
|||
|a0 @File1 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2 |
|||
|b0 @File2 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2 |
|||
|0100 |
|||
=={{header|Visual Basic .NET}}== |
|||
;in-file .File1/name DEO2 |
|||
{{works with|Visual Basic .NET|9.0+}} |
|||
;out-file .File2/name DEO2 |
|||
&loop |
|||
<lang vbnet>'byte copy |
|||
#0100 .File1/length DEO2k POP |
|||
My.Computer.FileSystem.WriteAllBytes("output.txt", _ |
|||
;buffer .File1/read DEO2 |
|||
My.Computer.FileSystem.ReadAllBytes("input.txt"), False) |
|||
.File1/success DEI2 |
|||
'text copy |
|||
.File2/length DEO2k POP |
|||
Using input = IO.File.OpenText("input.txt"), _ |
|||
;buffer .File2/write DEO2 |
|||
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt")) |
|||
output.Write(input.ReadToEnd) |
|||
EQU2 ?&loop |
|||
End Using |
|||
#80 .System/state DEO |
|||
'Line by line text copy |
|||
BRK |
|||
Using input = IO.File.OpenText("input.txt"), _ |
|||
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt")) |
|||
@in-file "input.txt 00 |
|||
Do Until input.EndOfStream |
|||
@out-file "output.txt 00 |
|||
output.WriteLine(input.ReadLine) |
|||
@buffer $100</syntaxhighlight> |
|||
Loop |
|||
End Using</lang> |
|||
=={{header|Vedit macro language}}== |
|||
An edit buffer is normally used as "string variable" in Vedit. |
|||
To read a file into edit buffer, simply open the file. The file contents can then be modified if required before saving into a new file. |
|||
<syntaxhighlight lang="vedit">File_Open("input.txt") |
|||
File_Save_As("output.txt", NOMSG) |
|||
Buf_Close(NOMSG) </syntaxhighlight> |
|||
=={{header|Wart}}== |
|||
<syntaxhighlight lang="wart">with infile "input.txt" |
|||
with outfile "output.txt" |
|||
whilet line (read_line) |
|||
prn line</syntaxhighlight> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">import "io" for File |
|||
var contents = File.read("input.txt") |
|||
File.create("output.txt") {|file| |
|||
file.writeBytes(contents) |
|||
}</syntaxhighlight> |
|||
=={{header|XPL0}}== |
|||
Usage: fileio <input.txt >output.txt |
|||
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
|||
int I, C; |
|||
char IntermediateVariable; |
|||
[IntermediateVariable:= GetHp; |
|||
I:= 0; |
|||
repeat C:= ChIn(1); |
|||
IntermediateVariable(I):= C; |
|||
I:= I+1; |
|||
until C = $1A; \EOF |
|||
I:= 0; |
|||
repeat C:= IntermediateVariable(I); |
|||
I:= I+1; |
|||
ChOut(0, C); |
|||
until C = $1A; \EOF |
|||
]</syntaxhighlight> |
|||
=={{header|zkl}}== |
|||
<syntaxhighlight lang="zkl">var d=File("input.txt").read(); |
|||
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy |
|||
File("output.txt").pump(Console); // verify by printing</syntaxhighlight> |
|||
It might be considered "good form" to immediately close files (rather than wait for the garbage collector to do it) as these are system resources. |
|||
<syntaxhighlight lang="zkl">var in=File("input.txt"), out=File("output.txt","w"); |
|||
foreach line in (in) { out.write(line) } // copy line by line |
|||
out.close(); // or out=Void and let GC close the file</syntaxhighlight> |
|||
<syntaxhighlight lang="zkl">fin,fout:=File("input.txt","rb"), File("output.txt","wb"); // copy in chunks, implicit buffer |
|||
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();</syntaxhighlight> |
|||
<syntaxhighlight lang="zkl">// copy in chunks, let GC close file handles |
|||
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));</syntaxhighlight> |
|||
In these last two, the implicit buffer (whose size if given by the numbers) is visible inside the pump. Consider this example, which converts input to upper case text on its way to output (the Data() is optional; using it chunks, without, lines): |
|||
<syntaxhighlight lang="zkl">File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");</syntaxhighlight> |
|||
=={{header|Zig}}== |
|||
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1357+10d03acdb |
|||
<syntaxhighlight lang="zig">const std = @import("std"); |
|||
pub fn main() (error{OutOfMemory} || std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.WriteError)!void { |
|||
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; |
|||
defer _ = gpa.deinit(); |
|||
const allocator = gpa.allocator(); |
|||
const cwd = std.fs.cwd(); |
|||
var input_file = try cwd.openFile("input.txt", .{ .mode = .read_only }); |
|||
defer input_file.close(); |
|||
var output_file = try cwd.createFile("output.txt", .{}); |
|||
defer output_file.close(); |
|||
// Restrict input_file's size to "up to 10 MiB". |
|||
var input_file_content = try input_file.readToEndAlloc(allocator, 10 * 1024 * 1024); |
|||
defer allocator.free(input_file_content); |
|||
try output_file.writeAll(input_file_content); |
|||
return; |
|||
}</syntaxhighlight> |
|||
{{omit from|EasyLang}} |
|||
{{omit from|HTML}} |
|||
{{omit from|Order}} |
|||
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have a filesystem, just namespaced variables. --> |
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have a filesystem, just namespaced variables. --> |
||
{{omit from|Unlambda|Does not handle files.}} |
{{omit from|Unlambda|Does not handle files.}} |
Latest revision as of 15:24, 11 May 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
- how to read from a file into a variable
- how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
11l
V file_contents = File(‘input.txt’).read()
File(‘output.txt’, ‘w’).write(file_contents)
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readwrtFile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ TAILLEBUF, 1000
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessErreur: .asciz "Error open input file.\n"
szMessErreur4: .asciz "Error open output file.\n"
szMessErreur1: .asciz "Error close file.\n"
szMessErreur2: .asciz "Error read file.\n"
szMessErreur3: .asciz "Error write output file.\n"
/*************************************************/
szMessCodeErr: .asciz "Error code décimal : @ \n"
szNameFileInput: .asciz "input.txt"
szNameFileOutput: .asciz "output.txt"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sBuffer: .skip TAILLEBUF
sZoneConv: .skip 24
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main
main: // entry of program
mov x0,AT_FDCWD
ldr x1,qAdrszNameFileInput // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN // call system OPEN
svc #0
cmp x0,0 // open error ?
ble erreur
mov x19,x0 // save File Descriptor
ldr x1,qAdrsBuffer // buffer address
mov x2,TAILLEBUF // buffer size
mov x8,READ // call system READ
svc 0
cmp x0,0 // read error ?
ble erreur2
mov x20,x0 // length read characters
// close imput file
mov x0,x19 // Fd
mov x8,CLOSE // call system CLOSE
svc 0
cmp x0,0 // close error ?
blt erreur1
// create output file
mov x0,AT_FDCWD
ldr x1,qAdrszNameFileOutput // file name
mov x2,O_CREAT|O_RDWR // flags
ldr x3,qFicMask1 // Mode
mov x8,OPEN // call system open file
svc 0
cmp x0,#0 // create error ?
ble erreur4
mov x19,x0 // file descriptor
ldr x1,qAdrsBuffer
mov x2,x20 // length to write
mov x8, #WRITE // select system call 'write'
svc #0 // perform the system call
cmp x0,#0 // error write ?
blt erreur3
// close output file
mov x0,x19 // Fd fichier
mov x8, #CLOSE // call system CLOSE
svc #0
cmp x0,#0 // error close ?
blt erreur1
mov x0,#0 // return code OK
b 100f
erreur:
ldr x1,qAdrszMessErreur
bl displayError
mov x0,#1 // error return code
b 100f
erreur1:
ldr x1,qAdrszMessErreur1
bl displayError
mov x0,#1 // error return code
b 100f
erreur2:
ldr x1,qAdrszMessErreur2
bl displayError
mov x0,#1 // error return code
b 100f
erreur3:
ldr x1,qAdrszMessErreur3
bl displayError
mov x0,#1 // error return code
b 100f
erreur4:
ldr x1,qAdrszMessErreur4
bl displayError
mov x0,#1 // error return code
b 100f
100: // end program
mov x8,EXIT
svc 0
qAdrszNameFileInput: .quad szNameFileInput
qAdrszNameFileOutput: .quad szNameFileOutput
qAdrszMessErreur: .quad szMessErreur
qAdrszMessErreur1: .quad szMessErreur1
qAdrszMessErreur2: .quad szMessErreur2
qAdrszMessErreur3: .quad szMessErreur3
qAdrszMessErreur4: .quad szMessErreur4
qAdrsBuffer: .quad sBuffer
qFicMask1: .quad 0644
/******************************************************************/
/* display error message */
/******************************************************************/
/* x0 contains error code */
/* x1 contains address error message */
displayError:
stp x2,lr,[sp,-16]! // save registers
mov x2,x0 // save error code
mov x0,x1 // display message error
bl affichageMess
mov x0,x2
ldr x1,qAdrsZoneConv // conversion error code
bl conversion10S // decimal conversion
ldr x0,qAdrszMessCodeErr
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message final
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
qAdrszMessCodeErr: .quad szMessCodeErr
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
ACL2
:set-state-ok t
(defun read-channel (channel limit state)
(mv-let (ch state)
(read-char$ channel state)
(if (or (null ch)
(zp limit))
(let ((state (close-input-channel channel state)))
(mv nil state))
(mv-let (so-far state)
(read-channel channel (1- limit) state)
(mv (cons ch so-far) state)))))
(defun read-from-file (filename limit state)
(mv-let (channel state)
(open-input-channel filename :character state)
(mv-let (contents state)
(read-channel channel limit state)
(mv (coerce contents 'string) state))))
(defun write-channel (channel cs state)
(if (endp cs)
(close-output-channel channel state)
(let ((state (write-byte$ (char-code (first cs))
channel state)))
(let ((state (write-channel channel
(rest cs)
state)))
state))))
(defun write-to-file (filename str state)
(mv-let (channel state)
(open-output-channel filename :byte state)
(write-channel channel (coerce str 'list) state)))
(defun copy-file (in out state)
(mv-let (contents state)
(read-from-file in (expt 2 40) state)
(write-to-file out contents state)))
Action!
The attached result has been obtained under DOS 2.5.
INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit
PROC Dir(CHAR ARRAY filter)
BYTE dev=[1]
CHAR ARRAY line(255)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC CopyFile(CHAR ARRAY src,dst)
DEFINE BUF_LEN="1000"
BYTE in=[1], out=[2]
BYTE ARRAY buff(BUF_LEN)
CARD len
Close(in)
Close(out)
Open(in,src,4)
Open(out,dst,8)
DO
len=Bget(in,buff,BUF_LEN)
IF len>0 THEN
Bput(out,buff,len)
FI
UNTIL len#BUF_LEN
OD
Close(in)
Close(out)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*",
src="D:INPUT.TXT", dst="D:OUTPUT.TXT"
Put(125) PutE() ;clear screen
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Copy ""%S"" to ""%S""%E%E",src,dst)
CopyFile(src,dst)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Dir "D:*.*" DOS SYS 037 DUP SYS 042 INPUT TXT 011 617 FREE SECTORS Copy "D:INPUT.TXT" to "D:OUTPUT.TXT" Dir "D:*.*" DOS SYS 037 DUP SYS 042 INPUT TXT 011 OUTPUT TXT 011 606 FREE SECTORS
Ada
Line by line
Assuming everything is fine and no error handling is required, this solution is sufficient:
with Ada.Text_IO; use Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Input, Output : File_Type;
begin
Open (File => Input,
Mode => In_File,
Name => "input.txt");
Create (File => Output,
Mode => Out_File,
Name => "output.txt");
loop
declare
Line : String := Get_Line (Input);
begin
-- You can process the contents of Line here.
Put_Line (Output, Line);
end;
end loop;
Close (Input);
Close (Output);
exception
when End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;
Expanded with proper error handling and reporting it reads:
with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO;
procedure Read_And_Write_File_Line_By_Line is
Read_From : constant String := "input.txt";
Write_To : constant String := "output.txt";
Input, Output : File_Type;
begin
begin
Open (File => Input,
Mode => In_File,
Name => Read_From);
exception
when others =>
Put_Line (Standard_Error,
"Can not open the file '" & Read_From & "'. Does it exist?");
Set_Exit_Status (Failure);
return;
end;
begin
Create (File => Output,
Mode => Out_File,
Name => Write_To);
exception
when others =>
Put_Line (Standard_Error,
"Can not create a file named '" & Write_To & "'.");
Set_Exit_Status (Failure);
return;
end;
loop
declare
Line : String := Get_Line (Input);
begin
-- You can process the contents of Line here.
Put_Line (Output, Line);
end;
end loop;
Close (Input);
Close (Output);
exception
when End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Read_And_Write_File_Line_By_Line;
Character by character
The following example reads and writes each file one character at a time. (You should of course add error reporting as in the example above.)
with Ada.Sequential_IO;
procedure Read_And_Write_File_Character_By_Character is
package Char_IO is new Ada.Sequential_IO (Character);
use Char_IO;
Input, Output : File_Type;
Buffer : Character;
begin
Open (File => Input, Mode => In_File, Name => "input.txt");
Create (File => Output, Mode => Out_File, Name => "output.txt");
loop
Read (File => Input, Item => Buffer);
Write (File => Output, Item => Buffer);
end loop;
Close (Input);
Close (Output);
exception
when End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Read_And_Write_File_Character_By_Character;
Using Ada.Text_IO.Text_Streams
The following solution uses stream I/O. Any file of Ada.Text_IO can be used to obtain a corresponding stream. Reading and writing streams is more efficient than reading text files directly, because it skips formatting.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;
procedure Using_Text_Streams is
Input, Output : File_Type;
Buffer : Character;
begin
Open (File => Input, Mode => In_File, Name => "input.txt");
Create (File => Output, Mode => Out_File, Name => "output.txt");
loop
Buffer := Character'Input (Stream (Input));
Character'Write (Stream (Output), Buffer);
end loop;
Close (Input);
Close (Output);
exception
when End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Using_Text_Streams;
Aime
file i, o;
text s;
i.open("input.txt", OPEN_READONLY, 0);
o.open("output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY,
0644);
while (i.line(s) ^ -1) {
o.text(s);
o.byte('\n');
}
ALGOL 68
PROC copy file v1 = (STRING in name, out name)VOID: (
# note: algol68toc-1.18 - can compile, but not run v1 #
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
BOOL in ended := FALSE;
PROC call back ended = (REF FILE f) BOOL: in ended := TRUE;
on logical file end(in file, call back ended);
STRING line;
WHILE
get(in file, (line, new line));
# WHILE # NOT in ended DO # break to avoid excess new line #
put(out file, (line, new line))
OD;
ended:
close(in file);
close(out file)
);
PROC copy file v2 = (STRING in name, out name)VOID: (
INT errno;
FILE in file, out file;
errno := open(in file, in name, stand in channel);
errno := open(out file, out name, stand out channel);
PROC call back ended = (REF FILE f) BOOL: GO TO done;
on logical file end(in file, call back ended);
STRING line;
DO
get(in file, line);
put(out file, line);
get(in file, new line);
put(out file, new line)
OD;
done:
close(in file);
close(out file)
);
test:(
copy file v2("input.txt","output.txt")
)
AppleScript
on copyFile from src into dst
set filedata to read file src
set outfile to open for access dst with write permission
write filedata to outfile
close access outfile
end copyFile
copyFile from ":input.txt" into ":output.txt"
ARM Assembly
/* ARM assembly Raspberry PI */
/* program readwrtfile.s */
/*********************************************/
/*constantes */
/********************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3
.equ WRITE, 4
.equ OPEN, 5
.equ CLOSE, 6
.equ CREATE, 8
/* file */
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ TAILLEBUF, 1000
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessErreur: .asciz "Erreur ouverture fichier input.\n"
szMessErreur4: .asciz "Erreur création fichier output.\n"
szMessErreur1: .asciz "Erreur fermeture fichier.\n"
szMessErreur2: .asciz "Erreur lecture fichier.\n"
szMessErreur3: .asciz "Erreur d'écriture dans fichier de sortie.\n"
szRetourligne: .asciz "\n"
szMessErr: .ascii "Error code : "
sDeci: .space 15,' '
.asciz "\n"
szNameFileInput: .asciz "input.txt"
szNameFileOutput: .asciz "output.txt"
/*******************************************/
/* DONNEES NON INITIALISEES */
/*******************************************/
.bss
sBuffer: .skip TAILLEBUF
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main
main:
push {fp,lr} /* save registers */
ldr r0,iAdrszNameFileInput @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ call system OPEN
swi #0
cmp r0,#0 @ open error ?
ble erreur
mov r8,r0 @ save File Descriptor
ldr r1,iAdrsBuffer @ buffer address
mov r2,#TAILLEBUF @ buffer size
mov r7, #READ @ call system READ
swi 0
cmp r0,#0 @ read error ?
ble erreur2
mov r2,r0 @ length read characters
/* close imput file */
mov r0,r8 @ Fd
mov r7, #CLOSE @ call system CLOSE
swi 0
cmp r0,#0 @ close error ?
blt erreur1
@ create output file
ldr r0,iAdrszNameFileOutput @ file name
ldr r1,iFicMask1 @ flags
mov r7, #CREATE @ call system create file
swi 0
cmp r0,#0 @ create error ?
ble erreur4
mov r0,r8 @ file descriptor
ldr r1,iAdrsBuffer
@ et r2 contains the length to write
mov r7, #WRITE @ select system call 'write'
swi #0 @ perform the system call
cmp r0,#0 @ error write ?
blt erreur3
@ close output file
mov r0,r8 @ Fd fichier
mov r7, #CLOSE @ call system CLOSE
swi #0
cmp r0,#0 @ error close ?
blt erreur1
mov r0,#0 @ return code OK
b 100f
erreur:
ldr r1,iAdrszMessErreur
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur1:
ldr r1,iAdrszMessErreur1
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur2:
ldr r1,iAdrszMessErreur2
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur3:
ldr r1,iAdrszMessErreur3
bl afficheerreur
mov r0,#1 @ error return code
b 100f
erreur4:
ldr r1,iAdrszMessErreur4
bl afficheerreur
mov r0,#1 @ error return code
b 100f
100: @ end program
pop {fp,lr} /* restaur des 2 registres */
mov r7, #EXIT /* appel fonction systeme pour terminer */
swi 0
iAdrszNameFileInput: .int szNameFileInput
iAdrszNameFileOutput: .int szNameFileOutput
iAdrszMessErreur: .int szMessErreur
iAdrszMessErreur1: .int szMessErreur1
iAdrszMessErreur2: .int szMessErreur2
iAdrszMessErreur3: .int szMessErreur3
iAdrszMessErreur4: .int szMessErreur4
iAdrsBuffer: .int sBuffer
iFicMask1: .octa 0644
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} /* save registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* display error message */
/***************************************************/
/* r0 contains error code r1 address error message */
afficheerreur:
push {r1-r2,lr} @ save registers
mov r2,r0 @ save error code
mov r0,r1 @ address error message
bl affichageMess @ display error message
mov r0,r2 @ error code
ldr r1,iAdrsDeci @ result address
bl conversion10S
ldr r0,iAdrszMessErr @ display error code
bl affichageMess
pop {r1-r2,lr} @ restaur registers
bx lr @ return function
iAdrszMessErr: .int szMessErr
iAdrsDeci: .int sDeci
/***************************************************/
/* Converting a register to a signed decimal */
/***************************************************/
/* r0 contains value and r1 area address */
conversion10S:
push {r0-r4,lr} @ save registers
mov r2,r1 /* debut zone stockage */
mov r3,#'+' /* par defaut le signe est + */
cmp r0,#0 @ negative number ?
movlt r3,#'-' @ yes
mvnlt r0,r0 @ number inversion
addlt r0,#1
mov r4,#10 @ length area
1: @ start loop
bl divisionPar10R
add r1,#48 @ digit
strb r1,[r2,r4] @ store digit on area
sub r4,r4,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b
strb r3,[r2,r4] @ store signe
subs r4,r4,#1 @ previous position
blt 100f @ if r4 < 0 -> end
mov r1,#' ' @ space
2:
strb r1,[r2,r4] @store byte space
subs r4,r4,#1 @ previous position
bge 2b @ loop if r4 > 0
100:
pop {r0-r4,lr} @ restaur registers
bx lr
/***************************************************/
/* division for 10 fast unsigned */
/***************************************************/
@ r0 contient le dividende
@ r0 retourne le quotient
@ r1 retourne le reste
divisionPar10R:
push {r2,lr} @ save registers
sub r1, r0, #10 @ calcul de r0 - 10
sub r0, r0, r0, lsr #2 @ calcul de r0 - (r0 /4)
add r0, r0, r0, lsr #4 @ calcul de (r0-(r0/4))+ ((r0-(r0/4))/16
add r0, r0, r0, lsr #8 @ etc ...
add r0, r0, r0, lsr #16
mov r0, r0, lsr #3
add r2, r0, r0, asl #2
subs r1, r1, r2, asl #1 @ calcul (N-10) - (N/10)*10
addpl r0, r0, #1 @ regul quotient
addmi r1, r1, #10 @ regul reste
pop {r2,lr}
bx lr
Arturo
source: read "input.txt"
write "output.txt" source
print source
AutoHotkey
Method 1: the input file can be processed line by line.
Loop, Read, input.txt, output.txt
FileAppend, %A_LoopReadLine%`n
Method 2: the input file can be read at once if it is less than 1 GB.
FileRead, var, input.txt
FileAppend, %var%, output.txt
Method 3: the file can be copied without I/O.
FileCopy, input.txt, output.txt
Binary I/O is possible with this library from Laszlo.
AWK
(This does not handle properly binary files)
BEGIN {
while ( (getline <"input.txt") > 0 ) {
print >"output.txt"
}
}
Babel
(main
{ "input.txt" >>> -- File is now on stack
foo set -- File is now in 'foo'
foo "output.txt" <<< })
The spirit of Babel is to manipulate things on the stack whenever feasible. In this example, I showed how to save it into a symbolic variable (foo) but this step would not be necessary for many simple file-processing tasks, such as splitting on newlines or spaces.
Also note that the >>> (slurp) and <<< (spit) operators only handle "small" files - the limit is configurable but the default limit is 100MB. If you want to open very large files or if you need to perform a lot of interactive file I/O, Babel provides operators that wrap the C standard library fopen()/fclose() functions.
BASIC
Applesoft BASIC
This is only meant to copy a sequential text file. It is very unlikely that this works copying a random access text file.
100 I$ = "INPUT.TXT"
110 O$ = "OUTPUT.TXT"
120 M$ = CHR$(13)
130 D$ = CHR$(4)
140 PRINT D$"VERIFY"I$
150 PRINT D$"OPEN"O$
160 PRINT D$"DELETE"O$
170 PRINT D$"OPEN"O$
180 PRINT D$"OPEN"I$
190 PRINT D$"READ"I$
200 ONERR GOTO 280
210 GET C$
220 POKE 216,0
230 PRINT M$D$"WRITE"O$",B"B
240 B = B + 1
250 P = 2 - (C$ <> M$)
260 PRINT MID$(C$, P)
270 GOTO 190
280 POKE 216,0
290 EOF = PEEK(222) = 5
300 IF NOT EOF THEN RESUME
310 PRINT M$D$"CLOSE"
BaCon
text$ = LOAD$("input.txt")
SAVE text$ TO "output.txt"
BASIC256
open 1, "input.txt"
open 2, "output.txt"
while not eof(1)
linea$ = readline(1)
write 2, linea$
end while
close 1
close 2
BBC BASIC
BBC BASIC for Windows has a file copy command:
*COPY input.txt output.txt
Alternatively the copy can be done explicitly:
infile% = OPENIN("input.txt")
outfile% = OPENOUT("output.txt")
WHILE NOT EOF#infile%
BPUT #outfile%, BGET#infile%
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
Commodore BASIC
10 print chr$(14) : rem switch to upper+lower case set
20 print "read seq file input.txt and write to seq file output.txt"
30 open 4,8,4,"input.txt,seq,read"
40 open 8,8,8,"@:output.txt,seq,write" : rem '@'== new file
50 for i=0 to 1 : rem while i==0
60 input#4,a$
70 i=64 and st : rem check bit 6=='end of file'
80 print a$
90 print#8,a$
100 next : rem end while
110 close 4
120 close 8
130 end
FreeBASIC
' FB 1.05.0 Win64
/'
input.txt contains:
The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
'/
Open "output.txt" For Output As #1
Open "input.txt" For Input As #2
Dim line_ As String ' note that line is a keyword
While Not Eof(2)
Line Input #2, line_
Print #1, line_
Wend
Close #2
Close #1
- Output:
output.txt contains: The quick brown fox jumps over the lazy dog. Empty vessels make most noise. Too many chefs spoil the broth. A rolling stone gathers no moss.
FutureBasic
Modified May 2024 Prompts the user for an input text file. Rich Love
/*
Rosetta Code File input/output example
FutureBasic 7.0.24
Rich Love
5/11/24
*/
output file "FileInputOutput.app"
void Local fn doIt
CFURLRef ParentDirectory // Create a url for the desktop
ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
CFURLRef outputURL // Create a url for output.txt on the desktop
outputURL = fn URLByAppendingPathComponent( ParentDirectory, @"output.txt" )
CFURLRef inputURL = openpanel( 1, @"Open a text file",@"txt")
if inputURL = NULL then end
str255 dataLine
dataLine = ""
if fn FileManagerContentsAtURL(inputURL) <> NULL
open "I", 1, inputURL
open "O", 2, outputURL
While Not Eof(1)
Line Input #1, dataLine
Print #2, dataLine
Wend
Close #2
Close #1
alert 3,,@"File created on Desktop",@"output.txt",@"OK"
end
else
alert 3,,@"File Not Found on Desktop",@"input.txt",@"OK"
end
end if
end fn
void local fn DoAppEvent( ev as long )
select (ev)
case _appDidFinishLaunching
fn doIt
end select
end fn
on AppEvent fn DoAppEvent
handleevents
Gambas
Public Sub Main()
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored
File.Save(User.Home &/ "output.txt", sOutput)
File.Save(User.Home &/ "input.txt", sOutput & sInput)
Print "'input.txt' contains - " & sOutput & sInput
Print "'output.txt' contains - " & sOutput
End
Output:
'input.txt' contains - Hello World! 'output.txt' contains - Hello
IS-BASIC
100 STRING TX$*254
110 OPEN #1:"output.txt"
120 OPEN #2:"input.txt" ACCESS OUTPUT
130 WHEN EXCEPTION USE IOERROR
140 DO
150 LINE INPUT #1:TX$
160 PRINT #2:TX$
170 LOOP
180 END WHEN
190 HANDLER IOERROR
200 IF EXTYPE<>8001 THEN PRINT EXSTRING$(EXTYPE)
210 CLOSE #1
220 CLOSE #2
230 END HANDLER
Liberty BASIC
nomainwin
open "input.txt" for input as #f1
qtyBytes = lof( #f1)
source$ = input$( #f1, qtyBytes)
close #f1
open "output.txt" for output as #f2
#f2 source$;
close #f2
end
PureBasic
Basic file copy
CopyFile("input.txt","output.txt")
Line by line
in = ReadFile(#PB_Any,"input.txt")
If in
out = CreateFile(#PB_Any,"output.txt")
If out
Define MyLine$
While Not Eof(in)
MyLine$ = ReadString(in)
WriteString(out,MyLine$)
Wend
CloseFile(out)
EndIf
CloseFile(in)
EndIf
Reading & writing the complete file in one pass
If ReadFile(0,"input.txt")
Define MyLine$, *Buffer, length
length=FileSize("input.txt")
*Buffer = AllocateMemory(length)
If *Buffer
If OpenFile(1,"output.txt")
ReadData(0, *Buffer, length)
WriteData(1, *Buffer, length)
CloseFile(1)
EndIf
FreeMemory(*Buffer)
EndIf
CloseFile(0)
EndIf
QBasic
See QuickBASIC.
QuickBASIC
' File input/output
OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
LINE INPUT #1, Data$
PRINT #2, Data$
LOOP
CLOSE #1
CLOSE #2
END
RapidQ
File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams.
The first version copies text line by line, as in the BASIC example.
$INCLUDE "rapidq.inc"
DIM File1 AS QFileStream
DIM File2 AS QFileStream
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
WHILE NOT File1.EOF
data$ = File1.ReadLine
File2.WriteLine(data$)
WEND
File1.Close
File2.Close
When just copying data, the code can be simplified by using the CopyFrom method.
(The second parameter for CopyFrom is number of bytes to copy, 0 = copy the whole file.)
$INCLUDE "rapidq.inc"
DIM File1 AS QFileStream
DIM File2 AS QFileStream
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
File2.CopyFrom(File1, 0)
File1.Close
File2.Close
REALbasic
Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
Run BASIC
open "input.txt" for input as #in
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
close #in
open "output.txt" for output as #out
print #out, fileData$ 'write entire fie
close #out
end
Or directly with no intermediate fileData$
open "input.txt" for input as #in
open "output.txt" for output as #out
fileLen = LOF(#in) 'Length Of File
print #out, input$(#in, fileLen) 'entire file
close #in
close #out
True BASIC
OPEN #1: NAME "input.txt", ORG TEXT, ACCESS INPUT, CREATE OLD
OPEN #2: NAME "output.txt", CREATE NEWOLD
ERASE #2
DO
LINE INPUT #1: linea$
PRINT #2: linea$
LOOP UNTIL END #1
CLOSE #1
CLOSE #2
END
VBA
Option Explicit
Sub Main()
Dim s As String, FF As Integer
'read a file line by line
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
While Not EOF(FF)
Line Input #FF, s
Debug.Print s
Wend
Close #FF
'read a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF
s = Input(LOF(1), #FF)
Close #FF
Debug.Print s
'write a file
FF = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF
Print #FF, s
Close #FF
End Sub
VBScript
One liner (-2 for system default encoding)
CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll
Visual Basic .NET
Byte copy
My.Computer.FileSystem.WriteAllBytes("output.txt", _
My.Computer.FileSystem.ReadAllBytes("input.txt"), False)
Text copy
Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
output.Write(input.ReadToEnd)
End Using
Line by line text copy
Using input = IO.File.OpenText("input.txt"), _
output As New IO.StreamWriter(IO.File.OpenWrite("output.txt"))
Do Until input.EndOfStream
output.WriteLine(input.ReadLine)
Loop
End Using
Yabasic
open "input.txt" for reading as #1
open "output.txt" for writing as #2
while not eof(1)
line input #1 linea$
print #2 linea$
wend
close #1
close #2
Batch File
copy input.txt output.txt
or
type input.txt > output.txt
or
for /f "" %L in ('more^<input.txt') do echo %L>>output.txt
There may be other techniques too.
BCPL
GET "libhdr"
LET start() BE $(
// Attempt to open the named files.
LET source = findinput("input.txt")
LET destination = findoutput("output.txt")
TEST source = 0 THEN
writes("Unable to open input.txt*N")
ELSE TEST destination = 0 THEN
writes("Unable to open output.txt*N")
ELSE $(
// The current character, initially unknown.
LET ch = ?
// Make the open files the current input and output streams.
selectinput(source)
selectoutput(destination)
// Copy the input to the output character by character until
// endstreamch is returned to indicate input is exhausted.
ch := rdch()
UNTIL ch = endstreamch DO $(
wrch(ch)
ch := rdch()
$)
// Close the currently selected streams.
endread()
endwrite()
$)
$)
Beef
using System;
using System.IO;
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
Befunge
0110"txt.tupni"#@i10"txt.tuptuo"#@o@
This linear program tries to open "input.txt" as text file (or aborts). It then writes the content in text mode (i.e. minus trailing spaces) to "output.txt" (or aborts).
BQN
data←•FBytes "input.txt"
"output.txt" •FBytes data
Bracmat
put$(get$"input.txt","output.txt",NEW)
C
#include <stdio.h>
int main(int argc, char **argv) {
FILE *in, *out;
int c;
in = fopen("input.txt", "r");
if (!in) {
fprintf(stderr, "Error opening input.txt for reading.\n");
return 1;
}
out = fopen("output.txt", "w");
if (!out) {
fprintf(stderr, "Error opening output.txt for writing.\n");
fclose(in);
return 1;
}
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
fclose(out);
fclose(in);
return 0;
}
A couple of remarks on the preceding example:
It uses fgetc
to read one character at a time. Each character is visited, even though there's nothing to do with it. Copying bigger blocks of data is much more efficient.
The following example addresses those issues. To avoid buffered I/O, it uses open(), read(), write() and close(), which are part of POSIX.
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
/* we just return a yes/no status; caller can check errno */
int copy_file(const char *in, const char *out)
{
int ret = 0;
int fin, fout;
ssize_t len;
char *buf[4096]; /* buffer size, some multiple of block size preferred */
struct stat st;
if ((fin = open(in, O_RDONLY)) == -1) return 0;
if (fstat(fin, &st)) goto bail;
/* open output with same permission */
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);
if (fout == -1) goto bail;
while ((len = read(fin, buf, 4096)) > 0)
write(fout, buf, len);
ret = len ? 0 : 1; /* last read should be 0 */
bail: if (fin != -1) close(fin);
if (fout != -1) close(fout);
return ret;
}
int main()
{
copy_file("infile", "outfile");
return 0;
}
If it's certain that mapping the whole input file into memory poses no problem (there can be all kinds of problems), this may be the most efficient:
int copy_file(const char *in, const char *out)
{
int ret = 0;
int fin, fout;
char *bi;
struct stat st;
if ((fin = open(in, O_RDONLY)) == -1) return 0;
if (fstat(fin, &st)) goto bail;
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);
if (fout == -1) goto bail;
bi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin, 0);
ret = (bi == (void*)-1)
? 0 : (write(fout, bi, st.st_size) == st.st_size);
bail: if (fin != -1) close(fin);
if (fout != -1) close(fout);
if (bi != (void*)-1) munmap(bi, st.st_size);
return ret;
}
C#
The long way:
using System.IO;
using (var reader = new StreamReader("input.txt"))
using (var writer = new StreamWriter("output.txt"))
{
var text = reader.ReadToEnd();
writer.Write(text);
}
The short way:
using System.IO;
var text = File.ReadAllText("input.txt");
File.WriteAllText("output.txt", text);
C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
if (output.is_open()) {
if (input.is_open()){
while (getline (input,line)) {
output << line << endl;
}
input.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close(); // Not necessary - will be closed when variable goes out of scope.
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
}
Simpler version:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
std::ifstream input("input.txt");
if (!input.is_open())
{
std::cerr << "could not open input.txt for reading.\n";
return EXIT_FAILURE;
}
std::ofstream output("output.txt");
if (!output.is_open())
{
std::cerr << "could not open output.txt for writing.\n";
return EXIT_FAILURE;
}
output << input.rdbuf();
if (!output)
{
std::cerr << "error copying the data.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Using istream- and ostream- iterators:
# include <algorithm>
# include <fstream>
int main() {
std::ifstream ifile("input.txt");
std::ofstream ofile("output.txt");
std::copy(std::istreambuf_iterator<char>(ifile),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(ofile));
}
Even simpler way:
#include <fstream>
int main()
{
std::ifstream input("input.txt");
std::ofstream output("output.txt");
output << input.rdbuf();
}
Clean
Define a function that copies the content from one file to another.
import StdEnv
copyFile fromPath toPath world
# (ok, fromFile, world) = fopen fromPath FReadData world
| not ok = abort ("Cannot open " +++ fromPath +++ " for reading")
# (ok, toFile, world) = fopen toPath FWriteData world
| not ok = abort ("Cannot open " +++ toPath +++ " for writing")
# (fromFile, toFile) = copyData 1024 fromFile toFile
# (ok, world) = fclose fromFile world
| not ok = abort ("Cannot close " +++ fromPath +++ " after reading")
# (ok, world) = fclose toFile world
| not ok = abort ("Cannot close " +++ toPath +++ " after writing")
= world
where
copyData bufferSize fromFile toFile
# (buffer, fromFile) = freads fromFile bufferSize
# toFile = fwrites buffer toFile
| size buffer < bufferSize = (fromFile, toFile) // we're done
= copyData bufferSize fromFile toFile // continue recursively
Apply this function to the world to copy a file.
Start world = copyFile "input.txt" "output.txt" world
Clojure
(use 'clojure.java.io)
(copy (file "input.txt") (file "output.txt"))
;; simple file writing
(spit "filename.txt" "your content here")
;; simple file reading
(slurp "filename.txt")
COBOL
COBOL 85
Flags used for Micro Focus COBOL:
$set ans85 flag"ans85" flagas"s" sequential"line"
identification division.
program-id. copyfile.
environment division.
input-output section.
file-control.
select input-file assign to "input.txt"
organization sequential
.
select output-file assign to "output.txt"
organization sequential
.
data division.
file section.
fd input-file.
1 input-record pic x(80).
fd output-file.
1 output-record pic x(80).
working-storage section.
1 end-of-file-flag pic 9 value 0.
88 eof value 1.
1 text-line pic x(80).
procedure division.
begin.
open input input-file
output output-file
perform read-input
perform until eof
write output-record from text-line
perform read-input
end-perform
close input-file output-file
stop run
.
read-input.
read input-file into text-line
at end
set eof to true
end-read
.
end program copyfile.
Implementation
IDENTIFICATION DIVISION.
PROGRAM-ID. file-io.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT in-file ASSIGN "input.txt"
ORGANIZATION LINE SEQUENTIAL.
SELECT OPTIONAL out-file ASSIGN "output.txt"
ORGANIZATION LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD in-file.
01 in-line PIC X(256).
FD out-file.
01 out-line PIC X(256).
PROCEDURE DIVISION.
DECLARATIVES.
in-file-error SECTION.
USE AFTER ERROR ON in-file.
DISPLAY "An error occurred while using input.txt."
GOBACK
.
out-file-error SECTION.
USE AFTER ERROR ON out-file.
DISPLAY "An error occurred while using output.txt."
GOBACK
.
END DECLARATIVES.
mainline.
OPEN INPUT in-file
OPEN OUTPUT out-file
PERFORM FOREVER
READ in-file
AT END
EXIT PERFORM
END-READ
WRITE out-line FROM in-line
END-PERFORM
CLOSE in-file, out-file
.
Built-in Subroutines
*> Originally from ACUCOBOL-GT
CALL "C$COPY" USING "input.txt", "output.txt", 0
*> Originally from Micro Focus COBOL
CALL "CBL_COPY_FILE" USING "input.txt", "output.txt"
ColdFusion
<cfif fileExists(expandPath("input.txt"))>
<cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
<cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif>
Common Lisp
By lines:
(with-open-file (in #p"input.txt" :direction :input)
(with-open-file (out #p"output.txt" :direction :output)
(loop for line = (read-line in nil 'foo)
until (eq line 'foo)
do (write-line line out))))
By arbitrary blocks and for possibly-binary files:
(defconstant +buffer-size+ (expt 2 16))
(with-open-file (in #p"input.txt" :direction :input
:element-type '(unsigned-byte 8))
(with-open-file (out #p"output.txt"
:direction :output
:element-type (stream-element-type in))
(loop with buffer = (make-array +buffer-size+
:element-type (stream-element-type in))
for size = (read-sequence buffer in)
while (plusp size)
do (write-sequence buffer out :end size))))
If you're on an odd platform which actually stores text/binary/... type information for files and your CL implementation will use this information, then in should be opened with :element-type :default.
D
import std.file: copy;
void main() {
copy("input.txt", "output.txt");
}
very plainly, with an intermediate variable:
void main() {
import std.file;
auto data = std.file.read("input.txt");
std.file.write("output.txt", data);
}
via an intermediate buffer variable:
import std.stdio;
int main() {
auto from = File("input.txt", "rb");
scope(exit) from.close();
auto to = File("output.txt", "wb");
scope(exit) to.close();
foreach(buffer; from.byChunk(new ubyte[4096*1024])) {
to.rawWrite(buffer);
}
return 0;
}
Copy the content from one file to another (exceptions are handled by Tango):
import tango.io.device.File;
void main()
{
auto from = new File("input.txt");
auto to = new File("output.txt", File.WriteCreate);
to.copy(from).close;
from.close;
}
Or a shorter example without explicitly closing the output file:
import tango.io.device.File;
void main()
{
auto to = new File("output.txt", File.WriteCreate);
to.copy(new File("input.txt")).close;
}
DBL
;
; File Input and output examples for DBL version 4 by Dario B.
;
RECORD CUSTOM
CUCOD, D5 ;customer code
CUNAM, A20 ;name
CUCIT, A20 ;city
, A55
;------- 100 bytes -------------
A80, A80
PROC
;--------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;suppress STOP message
CLOSE 1
OPEN (1,O,'TT:') ;open video
CLOSE 2
OPEN (2,O,"CUSTOM.DDF") ;create file in output
;Add new record
CLEAR CUSTOM
CUCOD=1
CUNAM="Alan Turing"
CUCIT="London"
WRITES (2,CUSTOM)
;Add new record
CLEAR CUSTOM
CUCOD=2
CUNAM="Galileo Galilei"
CUCIT="Pisa"
WRITES (2,CUSTOM)
;Modify a record
CLOSE 2
OPEN (2,U,"CUSTOM.DDF") [ERR=NOCUS] ;open in update
READ (2,CUSTOM,2) [ERR=NOREC]
CUCIT="Pisa - Italy"
WRITE (2,CUSTOM,2) [ERR=NOWRI]
;Add new record
CLOSE 2
OPEN (2,A,"CUSTOM.DDF") [ERR=NOCUS] ;open in append
CLEAR CUSTOM
CUCOD=3
CUNAM="Kenneth Lane Thompson"
CUCIT="New Orleans"
WRITES (2,CUSTOM)
CLOSE 2
;Read file and display a video
CLOSE 2
OPEN (2,I,"CUSTOM.DDF") [ERR=NOCUS]
DO FOREVER
BEGIN
READS (2,CUSTOM,EOF) [ERR=NOREC]
DISPLAY (1,13,CUSTOM)
END
EOF, DISPLAY (1,10)
CLOSE 2
;Write/read a text file
CLOSE 3
OPEN (3,O,"FILE.TXT")
DISPLAY (3,"An Occurrence at Owl Creek Bridge",13,10)
DISPLAY (3,"A man stood upon a railroad bridge in northern Alabama,",13,10)
DISPLAY (3,"looking down into the swift water twenty feet below.",13,10)
DISPLAY (3,"The man's hands were behind his back, the wrists bound ")
DISPLAY (3,"with a cord.",13,10)
CLOSE 3
OPEN (3,I,"FILE.TXT")
DO FOREVER
BEGIN
READS (3,A80,EOFF)
DISPLAY (1,A80(1:%TRIM(A80)),10)
END
EOFF, CLOSE 3
DISPLAY (1,10)
GOTO QUIT
;---------------------------------------------------------------
NOCUS, DISPLAY (1,10,"File CUSTUM.DDF Not found!",10)
GOTO QUIT
NOREC, DISPLAY (1,10,"Read error!",10)
GOTO QUIT
NOWRI, DISPLAY (1,10,"Write error!",10)
GOTO QUIT
QUIT, CLOSE 1
STOP
- Output:
00001Alan Turing London 00002Galileo Galilei Pisa - Italy 00003Kenneth Lane ThompsoNew Orleans An Occurrence at Owl Creek Bridge A man stood upon a railroad bridge in northern Alabama, looking down into the swift water twenty feet below. The man's hands were behind his back, the wrists bound with a cord.
DCL
$ open input input.txt
$ open /write output output.txt
$ loop:
$ read /end_of_file = done input line
$ write output line
$ goto loop
$ done:
$ close input
$ close output
Delphi
Delphi supports both typed and untyped as well as a textfile type for files. Delphi provides a default 128 byte buffer for text files. This may be enlarged via a call to SetTextBuff(Var F: Text; Var Buf [Size : integer]) procedure. All other files have no buffer at all and it is the programmers option to do buffering.
The following file I/O procedures have existed since Turbo Pascal V-3.
- Read(F,V1..Vn) - ReadLn(F,V1..Vn) - Write(F,V1[,V2..Vn]) - WriteLn(f,V1[,V2..Vn]) - BlockRead(F,Buff,BytesToRead[,BytesRead]) - BlockWrite(F,Buff,BytesToRead[,BytesWritten])
Files are opened using:
AssignFile(f,{fully qualified path and file name})
Assigns the file name to the file structure in preparation for opening.
Reset(f)
Opens and existing file. If it does not exist EIOError is raised.
Rewrite(f)
Creates a new file and opens it for I/O. If the files exists is is overwritten.
Delphi implemented Streams of which a variant is TFileStream and are very closely related to the Windows API for file handling.
- Text File I/O -
var
f : TextFile ;
s : string ;
begin
AssignFile(f,[fully qualified file name);
Reset(f);
writeln(f,s);
Reset(f);
ReadLn(F,S);
CloseFile(
end;
- Untyped File I/O -
This is perhaps one of the most powerful I/O functions built into Pascal. This will allow you to open and read a file of ANY type, regardless of structure, size or content. Note the usage of Reset(). This is using the optional size parameter that instructs the record size of file I/O. This could have been called with SizeOf(Buff) as the optional parameter but that would have limited flexibility. Calling it with a size of ONE byte allows you to adjust the buffer size on the fly, as conditions warrant. Also note the use of the BytesRead parameter. When included in the BlockRead() function it will return the number of bytes actually read. If this is not included, then if your directive to read n bytes is greater then the size of the file, the EOF will be encountered unexpectedly and EIOError will be raised.
var
f : File ;
buff : array[1.1024] of byte ;
BytesRead : Integer ;
begin
AssignFile(f,fully qualified file name);
Reset(f,1);
Blockread(f,Buff,SizeOf(Buff),BytesRead);
CloseFile(f);
end;
- Typed File I/O -
Typed file I/O is very useful when reading and writing structures. An Address List is quiet easy to write when using this type of I/O. The same file procedures are used with some subtle differences. Bite below in the blockread and blockwrite procedures that the bytes to read or write are 1. Also note that the reset procedure is not called with a buffer size. When performing Typed File I/O the size of the type definition is the buffer size. In the BlockRead() and BlockWrite() procedures I elected to read one record. Had I declared a very large buffer of type tAddressBook of say 500 records, I could have set bytes to read as SizeOf(Buffer) thereby reading a minimum of 500 records.
type
tAddressBook = Record
FName : string[20];
LName : string[30];
Address : string[30];
City : string[30];
State : string[2];
Zip5 : string[5];
Zip4 : string[4];
Phone : string[14];
Deleted : boolean ;
end;
var
f : file of tAddressBook ;
v : tAddressBook ;
bytes : integer ;
begin
AssignFile(f,fully qualified file name);
Reset(f);
Blockread(f,V,1,Bytes);
Edit(v);
Seek(F,FilePos(f)-1);
BlockWrite(f,v,1,bytes);
CloseFile(f);
end;
DIBOL-11
START ;Simple File Input and Output
RECORD TEMP
INLINE, A72
PROC
OPEN (8,I,"input.txt")
OPEN (9,O,"output.txt")
LOOP,
READS(8,TEMP,END)
WRITES(9,TEMP)
GOTO LOOP
END,
CLOSE 8
CLOSE 9
END
E
<file:output.txt>.setText(<file:input.txt>.getText())
(This version holds the entire contents in memory.)
Eiffel
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
create input_file.make_open_read ("input.txt")
create output_file.make_open_write ("output.txt")
from
input_file.read_character
until
input_file.exhausted
loop
output_file.put (input_file.last_character)
input_file.read_character
end
input_file.close
output_file.close
end
feature -- Access
input_file: PLAIN_TEXT_FILE
output_file: PLAIN_TEXT_FILE
end
Elena
ELENA 4.x :
import system'io;
public program()
{
var text := File.assign("input.txt").readContent();
File.assign("output.txt").saveContent(text);
}
Elixir
Read in the whole file and write the contents to a new file.
defmodule FileReadWrite do
def copy(path,new_path) do
case File.read(path) do
# In case of success, write to the new file
{:ok, body} ->
# Can replace with :write! to generate an error upon failure
File.write(new_path,body)
# If not successful, raise an error
{:error,reason} ->
# Using Erlang's format_error to generate error string
:file.format_error(reason)
end
end
end
FileReadWrite.copy("input.txt","output.txt")
Built in function:
File.cp!("input.txt", "output.txt")
Emacs Lisp
(defvar input (with-temp-buffer
(insert-file-contents "input.txt")
(buffer-string)))
(with-temp-file "output.txt"
(insert input))
Erlang
-module( file_io ).
-export( [task/0] ).
task() ->
{ok, Contents} = file:read_file( "input.txt" ),
ok = file:write_file( "output.txt", Contents ).
Euphoria
Read the entire file and then write it
include std/io.e
write_lines("output.txt", read_lines("input.txt"))
Line-by-line reading and writing
integer in,out
object line
in = open("input.txt","r")
out = open("output.txt","w")
while 1 do
line = gets(in)
if atom(line) then -- EOF reached
exit
end if
puts(out,line)
end while
close(out)
close(in)
F#
Using an intermediate variable for the input file content is not ideomatic in functional programming. Nevertheless...
open System.IO
let copyFile fromTextFileName toTextFileName =
let inputContent = File.ReadAllText fromTextFileName
inputContent |> fun text -> File.WriteAllText(toTextFileName, text)
[<EntryPoint>]
let main argv =
copyFile "input.txt" "output.txt"
0
Factor
Holds entire file content in memory:
"input.txt" binary file-contents
"output.txt" binary set-file-contents
A bit longer, but only holds a small amount of data in memory. If opening the file for writing fails, we want to clean up the file that's open for reading:
[
"input.txt" binary <file-reader> &dispose
"output.txt" binary <file-writer> stream-copy
] with-destructors
Possibly cheating:
"input.txt" "output.txt" copy-file
Forth
Forth traditionally has not had any file handling capabilities, preferring instead to operate on a disk image block by block. Most modern Forth systems however run under an existing operating system and provide methods for disk access.
\ <to> <from> copy-file
: copy-file ( a1 n1 a2 n2 -- )
r/o open-file throw >r
w/o create-file throw r>
begin
pad 84 2 pick read-file throw
?dup while
pad swap 3 pick write-file throw
repeat
close-file throw
close-file throw ;
\ Invoke it like this:
s" output.txt" s" input.txt" copy-file
Note the use of "2 pick" to get the input file handle and "3 pick" to get the output file handle. Local or global variables could have been used, but in this implementation simple stack manipulation was chosen. Also, only 84 bytes are copied at a time, as that is the maximum guaranteed size of "pad" the global memory area used to hold the data. For faster copies, allocating a larger buffer could be advantageous.
Also, abort" can be used instead of throw if desired.
A good practice is to ask the user the file name he wants to create like in this short example
: INPUT$ ( text -- n n )
pad swap accept pad swap ;
cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out
: get-content cr ." Enter your nickname : " 20 INPUT$ fd-out write-file cr ;
: close-output ( -- ) fd-out close-file throw ;
get-content
\ Inject a carriage return at end of file
s\" \n" fd-out write-file
close-output
bye
Fortran
It uses the access="stream" which is defined in Fortran 2003 standard and should allow to "copy" also binary data easily.
program FileIO
integer, parameter :: out = 123, in = 124
integer :: err
character :: c
open(out, file="output.txt", status="new", action="write", access="stream", iostat=err)
if (err == 0) then
open(in, file="input.txt", status="old", action="read", access="stream", iostat=err)
if (err == 0) then
err = 0
do while (err == 0)
read(unit=in, iostat=err) c
if (err == 0) write(out) c
end do
close(in)
end if
close(out)
end if
end program FileIO
Frink
contents = read["file:input.txt"]
w = new Writer["output.txt"]
w.print[contents]
w.close[]
GAP
CopyFile := function(src, dst)
local f, g, line;
f := InputTextFile(src);
g := OutputTextFile(dst, false);
while true do
line := ReadLine(f);
if line = fail then
break
else
WriteLine(g, Chomp(line));
fi;
od;
CloseStream(f);
CloseStream(g);
end;
GML
var file, str;
file = file_text_open_read("input.txt");
str = "";
while (!file_text_eof(file))
{
str += file_text_read_string(file);
if (!file_text_eof(file))
{
str += "
"; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind
file_text_readln(file);
}
}
file_text_close(file);
file = file_text_open_write("output.txt");
file_text_write_string(file,str);
file_text_close(file);
Go
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
Alternative solution is not a one-liner, but is one of "secondary interest" that copies data from one file to another without an intermediate variable.
package main
import (
"io"
"log"
"os"
)
func CopyFile(out, in string) (err error) {
var inf, outf *os.File
inf, err = os.Open(in)
if err != nil {
return
}
defer func() {
cErr := inf.Close()
if err == nil {
err = cErr
}
}()
outf, err = os.Create(out)
if err != nil {
return
}
_, err = io.Copy(outf, inf)
cErr := outf.Close()
if err == nil {
err = cErr
}
return
}
func main() {
if err := CopyFile("output.txt", "input.txt"); err != nil {
log.Fatal(err)
}
}
Groovy
Using File
content = new File('input.txt').text
new File('output.txt').write(content)
Using Ant
new AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)
Buffered
new File('output.txt').withWriter( w ->
new File('input.txt').withReader( r -> w << r }
}
GUISS
Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste,
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]
Haskell
Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.
main = readFile "input.txt" >>= writeFile "output.txt"
hexiscript
let in openin "input.txt"
let out openout "output.txt"
while !(catch (let c read char in))
write c out
endwhile
close in; close out
HicEst
Copy via system call:
CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)
Read and write line by line
OPEN(FIle=input, OLD, ERror=21) ! on error branch to label 21 (not shown)
OPEN(FIle=output)
DO i = 1, 1E300 ! "infinite" loop, exited on end-of-file error
READ( FIle=input, ERror=22) buffer ! on error (end of file) branch to label 22
WRITE(FIle=output, ERror=23) buffer ! on error branch to label 23 (not shown)
ENDDO
22 WRITE(FIle=output, CLoSe=1)
Read and write in 1 block
OPEN(FIle=input, SEQuential, UNFormatted, OLD, LENgth=len, ERror=31) ! on error branch to label 31 (not shown)
OPEN(FIle=output, SEQuential, UNFormatted, ERror=32) ! on error branch to label 32 (not shown)
ALLOCATE(c, len)
READ(FIle=input, CLoSe=1) c
WRITE(FIle=output, CLoSe=1) c END
i
software {
file = load("input.txt")
open("output.txt").write(file)
}
Icon and Unicon
Icon and Unicon I/O by default is line driven. This can be changed with options in open and by the use of reads() and writes().
IDL
; open two LUNs
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
; how many bytes to read
fs = fstat(unit2)
; make buffer
buff = bytarr(fs.size)
; transfer content
readu,unit2,buff
writeu,unit1,buff
; that's all
close,/all
Io
inf := File with("input.txt") openForReading
outf := File with("output.txt") openForUpdating
while(l := inf readLine,
outf write(l, "\n")
)
inf close
outf close
J
'output.txt' (1!:2~ 1!:1)&< 'input.txt'
Or using the system library files:
require 'files'
'output.txt' (fwrite~ fread) 'input.txt'
Note that J will read as many characters from the file as the system reports, for the size of the file. So if the system reports that the file is empty when it is not, J will return an empty result when using this file reading mechanism. (This can happen for "files" which really represent a connection to something else. When this happens, it's usually better to dedicate a separate process to reading the file.)
Java
Simple version; Files may be closed automatically by OS, on some systems.
import java.io.*;
public class FileIODemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("ouput.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
This version closes both files after without OS intervention.
import java.io.*;
public class FileIODemo2 {
public static void main(String args[]) {
try {
// Probably should wrap with a BufferedInputStream
final InputStream in = new FileInputStream("input.txt");
try {
// Probably should wrap with a BufferedOutputStream
final OutputStream out = new FileOutputStream("output.txt");
try {
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
out.close();
}
}
finally {
in.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
Package nio
import java.io.*;
import java.nio.channels.*;
public class FileIODemo3 {
public static void main(String args[]) {
try {
final FileChannel in = new FileInputStream("input.txt").getChannel();
try {
final FileChannel out = new FileOutputStream("output.txt").getChannel();
try {
out.transferFrom(in, 0, in.size());
}
finally {
out.close();
}
}
finally {
in.close();
}
}
catch (Exception e) {
System.err.println("Exception while trying to copy: "+e);
e.printStackTrace(); // stack trace of place where it happened
}
}
}
This version is more in line with the other languages' implementations: it assumes simple text files, and doesn't worry too much about errors (just throws them out to the caller, the console in this case). It's shorter and simpler and shows that simple programs can be simple to write, in Java as well.
import java.io.*;
public class Test {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
}
import java.nio.file.*;
public class Copy{
public static void main(String[] args) throws Exception{
FileSystem fs = FileSystems.getDefault();
Path in = fs.getPath("input.txt");
Path out = fs.getPath("output.txt");
Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
}
}
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
var f_out = fso.OpenTextFile('output.txt', ForWriting, true);
// for small files:
// f_out.Write( f_in.ReadAll() );
while ( ! f_in.AtEndOfStream) {
// ReadLine() does not include the newline char
f_out.WriteLine( f_in.ReadLine() );
}
f_in.Close();
f_out.Close();
var fs = require('fs');
require('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));
jq
If the input file consists of ordinary lines of text, then the lines can be copied verbatim, one by one, as follows:
jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt
If the input file consists of JSON entities, and if we wish to "pretty print" each, then the following will suffice:
jq -M '. as $line | $line' input.txt > output.txt
Note that the variable, $line, is included in the above programs solely to satisfy the task requirements. In practice, the jq program in both cases would normally be just: `.`
Julia
Here we read the content of file1 into the variable mystring. Then we write the content of string to file2.
mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w")
Note however that Julia has a `cp` function to copy the content of a file to another file.
cp("file1","file2")
We can also open and close the file handles manually.
infile = open("file1", "r")
outfile = open("file2", "w")
write(outfile, read(infile, String))
close(outfile)
close(infile)
Here is a one-liner that guarantees that the file handle is closed even if something goes wrong during the read/write phase.
open(IO ->write(IO, read("file1", String)), "file2", "w")
K
`output.txt 0:0:`input.txt
Kotlin
// version 1.1.2
import java.io.File
fun main(args: Array<String>) {
val text = File("input.txt").readText()
File("output.txt").writeText(text)
}
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lang
Text-based
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
$text = [[io]]::fp.readFile($fileIn)
[[io]]::fp.writeFile($fileOut, $text)
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
Byte-based
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
$fileIn = [[io]]::fp.openFile(input.txt)
$fileOut = [[io]]::fp.openFile(output.txt)
$bytes = [[io]]::fp.readBytes($fileIn)
[[io]]::fp.writeBytes($fileOut, $bytes)
[[io]]::fp.closeFile($fileIn)
[[io]]::fp.closeFile($fileOut)
Lang5
: puts(*) . "\n" . ;
: set-file '> swap open ;
: >>contents slurp puts ;
: copy-file
swap set-file 'fdst set fdst fout >>contents fdst close ;
'output.txt 'input.txt copy-file
Lingo
----------------------------------------
-- Returns file as ByteArray
-- @param {string} tFile
-- @return {byteArray|false}
----------------------------------------
on getBytes (tFile)
fp = xtra("fileIO").new()
fp.openFile(tFile, 1)
if fp.status() then return false
data = fp.readByteArray(fp.getLength())
fp.closeFile()
return data
end
----------------------------------------
-- Saves ByteArray to file
-- @param {string} tFile
-- @param {byteArray} tString
-- @return {bool} success
----------------------------------------
on putBytes (tFile, tByteArray)
fp = xtra("fileIO").new()
fp.openFile(tFile, 2)
err = fp.status()
if not (err) then fp.delete()
else if (err and not (err = -37)) then return false
fp.createFile(tFile)
if fp.status() then return false
fp.openFile(tFile, 2)
if fp.status() then return false
fp.writeByteArray(tByteArray)
fp.closeFile()
return true
end
data = getBytes("input.txt")
putBytes("output.txt", data)
Lisaac
Section Header
+ name := FILE_IO;
Section Public
- main <- (
+ e : ENTRY;
+ f : STD_FILE;
+ s : STRING;
e := FILE_SYSTEM.get "input.txt";
(e != NULL).if {
f ?= e.open_read_only;
(f != NULL).if {
s := STRING.create(f.size);
f.read s size (f.size);
f.close;
};
};
(s != NULL).if {
e := FILE_SYSTEM.make_file "output.txt";
(e != NULL).if {
f ?= e.open;
(f != NULL).if {
f.write s from (s.lower) size (s.count);
f.close;
};
};
};
);
Logo
to copy :from :to
openread :from
openwrite :to
setread :from
setwrite :to
until [eof?] [print readrawline]
closeall
end
copy "input.txt "output.txt
Lua
inFile = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
-- other options are "*line",
-- or the number of characters to read.
inFile:close()
outFile = io.open("output.txt", "w")
outfile:write(data)
outfile:close()
-- Oneliner version:
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))
M2000 Interpreter
Using Document Object
We can use Open for input/ Input$()/close, Open for Output/Print/close, but using a Document object is better, because Load.Doc can find the type of line breack and the coding, if it is UTF-8, UTG-16LE/BE and Ansi (we can provide another argument with specific way to open, or a Locale id for Ansi). When we save the document, we use the same format, so we preserve the coding and the line break type.
Open statement works for ANSI and using Wide for UTF-16LE only.
Here we use Edit to make Input.txt and edit some lines of text. Pressing Esc text saved to disk. Using Load.Doc we get the Input.txt, and we can display it using Report (which render text with word wrap, in M2000 console, using proportional text rendering), also if we have many lines there is a stop in each 3/4 of scrolling lines, to wait for a space bar or mouse click. After a wait for a keypress Doc$ saved to Output.txt, and we open it in editor.
We can use Edit.Doc to edit Doc$, without save and then open for edit.
We can edit thousands of lines. Document is a double linked list.
Module FileInputOutput {
Edit "Input.txt"
Document Doc$
Load.Doc Doc$, "Input.txt"
Report Doc$
Print "Press a key:";Key$
Save.Doc Doc$, "Output.txt"
Edit "Output.txt"
}
FileInputOutput
Using Buffer Object
A buffer expose real pointer (address), so here M(0) is the address of first byte, and Len(m) is the size of buffer in bytes. This buffer is not for code, but for data (no execution allowed).
Module Using_Buffer {
M=buffer("Input.txt")
Print Len(m)
Open "Output1.txt" For Wide Output as #F
Print #F, Eval$(M);
Close #F
Edit "Output1.txt"
z=Filelen("Output1.txt")
Print z
Open "OutputAscii.txt" For Output as #F
Print #F, Eval$(M);
Close #F
Print Filelen("OutputAscii.txt")=z/2
Edit "OutputAscii.txt"
}
Using_Buffer
Maple
inout:=proc(filename)
local f;
f:=FileTools[Text][ReadFile](filename);
FileTools[Text][WriteFile]("output.txt",f);
end proc;
Mathematica/Wolfram Language
SetDirectory@NotebookDirectory[];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]
MAXScript
inFile = openFile "input.txt"
outFile = createFile "output.txt"
while not EOF inFile do
(
format "%" (readLine inFile) to:outFile
)
close inFile
close outFile
Mercury
:- module file_io.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
main(!IO) :-
io.open_input("input.txt", InputRes, !IO),
(
InputRes = ok(Input),
io.read_file_as_string(Input, ReadRes, !IO),
(
ReadRes = ok(Contents),
io.close_input(Input, !IO),
io.open_output("output.txt", OutputRes, !IO),
(
OutputRes = ok(Output),
io.write_string(Output, Contents, !IO),
io.close_output(Output, !IO)
;
OutputRes = error(OutputError),
print_io_error(OutputError, !IO)
)
;
ReadRes = error(_, ReadError),
print_io_error(ReadError, !IO)
)
;
InputRes = error(InputError),
print_io_error(InputError, !IO)
).
:- pred print_io_error(io.error::in, io::di, io::uo) is det.
print_io_error(Error, !IO) :-
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, io.error_message(Error), !IO),
io.set_exit_status(1, !IO).
mIRC Scripting Language
alias Write2FileAndReadIt {
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
}
Modula-3
MODULE FileIO EXPORTS Main;
IMPORT IO, Rd, Wr;
<*FATAL ANY*>
VAR
infile: Rd.T;
outfile: Wr.T;
txt: TEXT;
BEGIN
infile := IO.OpenRead("input.txt");
outfile := IO.OpenWrite("output.txt");
txt := Rd.GetText(infile, LAST(CARDINAL));
Wr.PutText(outfile, txt);
Rd.Close(infile);
Wr.Close(outfile);
END FileIO.
The code <*FATAL ANY*>
is a pragma that tells the program to die if any exceptions (such as read/write errors) occur.
Nanoquery
import Nanoquery.IO
input = new(File, "input.txt")
output = new(File)
output.create("output.txt")
output.open("output.txt")
contents = input.readAll()
output.write(contents)
NetRexx
Takes advantage of some of the new path and file handling features of Java's java.nio library.
/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.nio.
parse arg infileName outfileName .
if infileName = '' | infileName.length = 0 then infileName = 'data/input.txt'
if outfileName = '' | outfileName.length = 0 then outfileName = 'data/output.txt'
binaryCopy(infileName, outfileName)
return
method binaryCopy(infileName, outfileName) public static
do
infile = Paths.get('.', [String infileName])
outfile = Paths.get('.', [String outfileName])
fileOctets = Files.readAllBytes(infile)
Files.write(outfile, fileOctets, [StandardOpenOption.WRITE, StandardOpenOption.CREATE])
catch ioex = IOException
ioex.printStackTrace()
end
return
Nim
Copying the file directly (without buffer):
import os
copyfile("input.txt", "output.txt")
Buffer for the entire file:
let x = readFile("input.txt")
writeFile("output.txt", x)
Line by line:
var
i = open("input.txt")
o = open("output.txt", fmWrite)
for line in i.lines:
o.writeLine(line)
i.close()
o.close()
With a fixed sized buffer:
const size = 4096
var
i = open("input.txt")
o = open("output.txt", fmWrite)
buf: array[size, char]
while i.readBuffer(buf.addr, size) > 0:
discard o.writeBuffer(buf.addr, size)
i.close()
o.close()
Using memory mapping:
import memfiles
var
i = memfiles.open("input.txt")
o = system.open("output.txt", fmWrite)
var written = o.writeBuffer(i.mem, i.size)
assert(written == i.size)
i.close()
o.close()
Nu
let text = open "input.txt"
$text | save "output.txt"
Objeck
use IO;
bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
len := File->Size("input.txt");
buffer := Byte->New[len];
in := FileReader->New("input.txt");
if(in->IsOpen() <> Nil) {
in->ReadBuffer(0, len, buffer);
out := FileWriter->New("output.txt");
if(out->IsOpen() <> Nil) {
out->WriteBuffer(0, len, buffer);
out->Close();
};
in->Close();
};
}
}
}
Object Pascal
For procedural code see the Delphi code, which is perfectly fine in ObjectPascal.
For a more object oriented style one can use a TFilestream:
uses
classes;
begin
with TFileStream.Create('input.txt', fmOpenRead) do
try
SaveToFile('output.txt');
finally
Free;
end;
end;
Objective-C
For copying files, using NSFileManager
is preferred:
[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];
If you want to do it manually:
NSData *data = [NSData dataWithContentsOfFile:@"input.txt"];
[data writeToFile:@"output.txt" atomically:YES];
Displayed without error checking to make it more clear. In real code you will need to add lot of error checking code, and maybe use dataWithContentsOfFile:error: if you want to get error information on failure. However, this code will mostly work correctly even if input does not exist or is not accessible. dataWithContentsOfFile: will return nil, and sending nil the message writeTofile:atomically: does nothing :-)
The second argument (atomically:YES) write the content to a temporary file, and rename the temporary file to the destination file, replacing existing file.
OCaml
By line:
let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
try
while true do
let s = input_line ic in
output_string oc s;
output_char oc '\n';
done
with End_of_file ->
close_in ic;
close_out oc;
;;
By character:
let () =
let ic = open_in "input.txt" in
let oc = open_out "output.txt" in
try
while true do
let c = input_char ic in
output_char oc c
done
with End_of_file ->
close_in ic;
close_out oc;
;;
(Notice that ic and oc, of type in_channel and out_channel, are buffered)
Octave
in = fopen("input.txt", "r", "native");
out = fopen("output.txt", "w","native");
if (in == -1)
disp("Error opening input.txt for reading.");
else
if (out == -1)
disp("Error opening output.txt for writing.");
else
while (1)
[val,count]=fread(in,1,"uchar",0,"native");
if (count > 0)
count=fwrite(out,val,"uchar",0,"native");
if (count == 0)
disp("Error writing to output.txt.");
end
else
break;
end
endwhile
end
end
if (in != -1)
fclose(in);
end
if (out != -1)
fclose(out);
end
Odin
package main
import "core:os"
main :: proc() {
data, ok := os.read_entire_file("input.txt")
defer delete(data)
ok = os.write_entire_file("output.txt", data)
}
Oforth
: fcopy(in, out)
| f g |
File newMode(in, File.BINARY) dup open(File.READ) ->f
File newMode(out, File.BINARY) dup open(File.WRITE) ->g
while(f >> dup notNull) [ g addChar ] drop
f close g close ;
Usage :
fcopy("input.txt", "output.txt")
OpenEdge/Progress
COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".
Oz
declare
class TextFile from Open.file Open.text end
In = {New TextFile init(name:"input.txt")}
Out = {New TextFile init(name:"output.txt" flags:[write text create truncate])}
proc {CopyAll In Out}
case {In getS($)} of false then skip
[] Line then
{Out putS(Line)}
{CopyAll In Out}
end
end
in
{CopyAll In Out}
{Out close}
{In close}
PARI/GP
f=read("filename.in");
write("filename.out", f);
Pascal
The | FreePascal wiki gives a detailed description. For procedureal code see the Delphi examples. The ObjectPascal example is more OO coding style.
Perl
#!/usr/bin/perl
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell
binmode $fh_out; # marks filehandle for binary content on systems where that matters
print $fh_out $_ while <$fh_in>;
# prints current line to file associated with $fh_out filehandle
# the same, less concise
#while (<$fh_in>) {
# print $fh_out $_;
#};
close $fh_in;
close $fh_out;
Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples.
Phix
whole file as a single string (safe on small binary files)
integer fn = open("input.txt","rb") string txt = get_text(fn) close(fn) fn = open("output.txt","wb") puts(fn,txt) close(fn)
line-by-line (text files only)
integer infn = open("input.txt","r"), outfn = open("output.txt","w") object line while 1 do line = gets(infn) if atom(line) then exit end if puts(outfn,line) end while close(infn) close(outfn)
byte-by-byte (safe on binary files)
integer byte, infd = open("input.txt","rb"), outfd = open("output.txt","wb") while 1 do byte = getc(infd) if byte=-1 then exit end if puts(outfd,byte) end while close(infd) close(outfd)
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/File_input/output
by Galileo, 10/2022 #/
def eof? dup -1 != enddef
"input.txt" "r" fopen
"output.txt" "w" fopen
over fgets
eof? while
over fputs
over fgets
eof? endwhile
drop fclose fclose
PHP
<?php
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
fclose($out);
fclose($in);
?>
<?php
if ($contents = file_get_contents('input.txt')) {
if (!file_put_contents('output.txt', $contents)) {
echo('Could not write output file.');
}
} else {
echo('Could not open input file.');
}
?>
PicoLisp
Using a variable
(let V (in "input.txt" (till))
(out "output.txt" (prin V)) )
Skipping intermediate variable
(in "input.txt"
(out "output.txt"
(echo) ) )
Pike
Line by line
object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
out->write(line + "\n");
Note that "\r" will be passed on like any other character. If line_iterator is called with the argument 1 it will however run in trim mode, and all "\r"s will be discarded.
PL/I
declare in file, out file;
open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input;
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output;
do forever;
get file (in) edit (line) (L);
put file (out) edit (line) (A);
end;
Pop11
Char by char copy:
lvars i_stream = discin('input.txt');
lvars o_stream = discout('output.txt');
lvars c;
while (i_stream() ->> c) /= termin do
o_stream(c);
endwhile;
Low level block copy:
lvars i_file = sysopen('input.txt', 0, true);
lvars o_file = syscreate('output.txt', 1, true);
lvars buff = inits(4096);
lvars i;
while (sysread(i_file, buff, length(buff)) ->> i) > 0 do
syswrite(o_file, buff, i);
endwhile;
PowerShell
Read the input file then pipe it's contents to output file. Assumes that the files are in the same folder that the script is executing in.
Get-Content $PWD\input.txt | Out-File $PWD\output.txt
Using an alternate cmdlet to write the file
Get-Content $PWD\input.txt | Set-Content $PWD\output.txt
Python
The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures that failure to open files raises appropriate exceptions, a restricted buffer is used to copy the files using binary mode, and any used file descriptors are always closed).
import shutil
shutil.copyfile('input.txt', 'output.txt')
However the following example shows how one would do file I/O of other sorts:
infile = open('input.txt', 'r')
outfile = open('output.txt', 'w')
for line in infile:
outfile.write(line)
outfile.close()
infile.close()
This does no error checking. A more robust program would wrap each open with exception handling blocks:
import sys
try:
infile = open('input.txt', 'r')
except IOError:
print >> sys.stderr, "Unable to open input.txt for input"
sys.exit(1)
try:
outfile = open('output.txt', 'w')
except IOError:
print >> sys.stderr, "Unable to open output.txt for output"
sys.exit(1)
try: # for finally
try: # for I/O
for line in infile:
outfile.write(line)
except IOError, e:
print >> sys.stderr, "Some I/O Error occurred (reading from input.txt or writing to output.txt)"
finally:
infile.close()
outfile.close()
In Python 2.6 (or 2.5 if we use from __future__ import with_statement) we can more simply write:
import sys
try:
with open('input.txt') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line)
except IOError:
print >> sys.stderr, "Some I/O Error occurred"
sys.exit(1)
The files will automatically be closed on exit of their with: blocks. (Thus even if an I/O error occurred while reading the middle of the input file we are assured that the .close() method will have been called on each of the two files.
Quackery
Assuming that input.txt
exists beforehand, and output.txt
does not (so we can safely drop
the success flag that file handling words return), and that we want both files to exist afterwards.
Quackery does not have variables, so instead we will move the file text to and from the ancillary stack temp
, leaving a copy on the top of temp
.
$ "input.txt" sharefile drop
temp put
temp share
$ "output.txt" putfile drop
R
If files are textual we can use readLines ("-1" means "read until the end")
src <- file("input.txt", "r")
dest <- file("output.txt", "w")
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest)
If the files are not textual but "generic":
src <- file("input.txt", "rb")
dest <- file("output.txt", "wb")
while( length(v <- readBin(src, "raw")) > 0 ) {
writeBin(v, dest)
}
close(src); close(dest)
Another simpler way is to use file.copy
file.copy("input.txt", "output.txt", overwrite = FALSE)
Racket
#lang racket
(define file-content
(with-input-from-file "input.txt"
(lambda ()
(let loop ((lst null))
(define new (read-char))
(if (eof-object? new)
(apply string lst)
(loop (append lst (list new))))))))
(with-output-to-file "output.txt"
(lambda ()
(write file-content)))
Raku
(formerly Perl 6)
If it is okay to have a temporary copy of the entire file in memory:
spurt "output.txt", slurp "input.txt";
Otherwise, copying line-by line:
my $in = open "input.txt";
my $out = open "output.txt", :w;
for $in.lines -> $line {
$out.say: $line;
}
$in.close;
$out.close;
Raven
'input.txt' read 'output.txt' write
REBOL
write %output.txt read %input.txt
; No line translations:
write/binary %output.txt read/binary %input.txt
; Save a web page:
write/binary %output.html read http://rosettacode.org
Red
file: read %input.txt
write %output.txt file
Retro
with files'
here dup "input.txt" slurp "output.txt" spew
REXX
In REXX, filename association is used rather than numeric stream numbers and explicit file opening is not required.
version 1
The two optional REXX statements are only needed if there is another REXX program in the invocation chain
(which may have invoked this program) that already has one of the input and/or output files open.
The two best programming practice REXX statements are only needed if there is another calling program in the invocation chain
(which may want to (re-)use the two files just used.
/*REXX program reads a file and copies the contents into an output file (on a line by line basis).*/
iFID = 'input.txt' /*the name of the input file. */
oFID = 'output.txt' /* " " " " output " */
call lineout iFID,,1 /*insure the input starts at line one.*/ /* ◄■■■■■■ optional.*/
call lineout oFID,,1 /* " " output " " " " */ /* ◄■■■■■■ optional.*/
do while lines(iFID)\==0; $=linein(iFID) /*read records from input 'til finished*/
call lineout oFID, $ /*write the record just read ──► output*/
end /*while*/ /*stick a fork in it, we're all done. */
call lineout iFID /*close input file, just to be safe.*/ /* ◄■■■■■■ best programming practice.*/
call lineout oFID /* " output " " " " " */ /* ◄■■■■■■ best programming practice.*/
version 2
Note that this version is limited to files less than one million bytes (and/or possibly virtual memory).
/*REXX program to read a file and write contents to an output file*****
* 03.09.2012 Walter Pachl (without erase string would be appended)
**********************************************************************/
ifid='input.txt' /*name of the input file. */
ofid='output.txt' /*name of the output file. */
'erase' ofid /* avoid appending */
s=charin(ifid,,1000000) /* read the input file */
Call charout ofid,s /* write to output file */
Ring
fn1 = "ReadMe.txt"
fn2 = "ReadMe2.txt"
fp = fopen(fn1,"r")
str = fread(fp, getFileSize(fp))
fclose(fp)
fp = fopen(fn2,"w")
fwrite(fp, str)
fclose(fp)
see "OK" + nl
func getFileSize fp
c_filestart = 0
c_fileend = 2
fseek(fp,0,c_fileend)
nfilesize = ftell(fp)
fseek(fp,0,c_filestart)
return nfilesize
Ruby
In general, open both files in binary mode.
str = File.open('input.txt', 'rb') {|f| f.read}
File.open('output.txt', 'wb') {|f| f.write str}
If 'input.txt' is a text file, we may forget binary mode. If no pathname begins with a pipe '|', then we may use IO::read and Kernel#open. (The pipe is a problem, because IO.read('| uname')
or open('| sh', 'w')
would open a subprocess and not a file.)
# Only if 'input.txt' is a text file!
# Only if pipe '|' is not first character of path!
str = IO.read('input.txt')
open('output.txt', 'w') {|f| f.write str}
To copy a file block by block, use FileUtils from the standard library.
require 'fileutils'
FileUtils.copy_file 'input.txt', 'output.txt'
Run BASIC
open "input.txt" for input as #in
fileLen = LOF(#in) 'Length Of File
fileData$ = input$(#in, fileLen) 'read entire file
close #in
open "output.txt" for output as #out
print #out, fileData$ 'write entire fie
close #out
end
Or directly with no intermediate fileData$
open "input.txt" for input as #in
open "output.txt" for output as #out
fileLen = LOF(#in) 'Length Of File
print #out, input$(#in, fileLen) 'entire file
close #in
close #out
Rust
fn main() {
let contents = std::fs::read("input.txt").expect("error reading input.txt");
std::fs::write("output.txt", contents).expect("error writing output.txt");
}
The above program will panic with any sort of error. The following shows proper error handling:
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::Path;
use std::{env, fmt, process};
fn main() {
let files: Vec<_> = env::args_os().skip(1).take(2).collect();
if files.len() != 2 {
exit_err("Both an input file and output file are required", 1);
}
copy(&files[0], &files[1]).unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));
}
fn copy<P: AsRef<Path>>(infile: P, outfile: P) -> io::Result<()> {
let mut vec = Vec::new();
Ok(try!(File::open(infile)
.and_then(|mut i| i.read_to_end(&mut vec))
.and_then(|_| File::create(outfile))
.and_then(|mut o| o.write_all(&vec))))
}
fn exit_err<T: fmt::Display>(msg: T, code: i32) -> ! {
writeln!(&mut io::stderr(), "ERROR: {}", msg).expect("Could not write to stdout");
process::exit(code);
}
S-BASIC
Surprisingly, S-BASIC has no EOF function, so we have to rely on error trapping to signal end of file. S-BASIC stores its error codes at 103H, and we can position a base-located variable there to retrieve it. The result is something of a kludge, but it works. Other S-BASIC preculiarities are explained by the comments.
comment
Preserve file channel #0 (the console) while declaring channels
#2 and #3 as sequential-access ASCII files.
end
files d, sa, sa
var s = string:255
based errcode = integer
base errcode at 103H
comment
CP/M expects upper case file names, but S-BASIC does not
automatically convert file name arguments to upper case, so we
have to do that ourself.
end
create "OUTPUT.TXT"
open #1,"INPUT.TXT"
open #2,"OUTPUT.TXT"
comment
S-BASIC allows alphanumeric line "numbers" (which are treated simply
as labels) as the target of GOTO and GOSUB statements, but the first
character must be a digit
end
on error goto 9done
rem - runtime error code 15 signals read past end of file
while errcode <> 15 do
begin
input3 #1; s
print #2; s
end
9done
close #1
close #2
end
Scala
import java.io.{ FileNotFoundException, PrintWriter }
object FileIO extends App {
try {
val MyFileTxtTarget = new PrintWriter("output.txt")
scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println)
MyFileTxtTarget.close()
} catch {
case e: FileNotFoundException => println(e.getLocalizedMessage())
case e: Throwable => {
println("Some other exception type:")
e.printStackTrace()
}
}
}
Scheme
Character by character copy
; Open ports for the input and output files
(define in-file (open-input-file "input.txt"))
(define out-file (open-output-file "output.txt"))
; Read and write characters from the input file
; to the output file one by one until end of file
(do ((c (read-char in-file) (read-char in-file)))
((eof-object? c))
(write-char c out-file))
; Close the ports
(close-input-port in-file)
(close-output-port out-file)
Seed7
The library osfiles.s7i contains the function copyFile which can be used to copy a source file to a destination.
$ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
begin
copyFile("input.txt", "output.txt");
end func;
SenseTalk
Reading the file all at once:
put file "input.txt" into fileContents
put fileContents into file "output.txt"
Reading the file line by line:
put "input.txt" into inputFile
put "output.txt" into outputFile
open file inputFile
open file outputFile for writing
repeat forever
read from file inputFile until return
if it is empty then exit repeat
write it to file outputFile
end repeat
close file inputFile
close file outputFile
Sidef
var in = %f'input.txt'.open_r;
var out = %f'output.txt'.open_w;
in.each { |line|
out.print(line);
};
Slate
(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
(File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
in >> out]]
Smalltalk
| in out |
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
[ in atEnd ]
whileFalse: [
out nextPut: (in next)
]
Snabel
Reads the entire file into into a list of buffers before writing and returns number of bytes written.
let: q Bin list;
'input.txt' rfile read {{@q $1 push} when} for
@q 'output.txt' rwfile write
0 $1 &+ for
Alternative solution for large files with comparable performance to shell cp; also returns number of bytes written.
let: q Bin list;
let: wq @q fifo;
let: w 'output.txt' rwfile @wq $1 write;
'input.txt' rfile read 0 $1 {{
$ @q $1 push
len +
@w &break _for
} when} for
@q +? {@w &_ for} when
SNOBOL4
input(.input,5,,'input.txt')
output(.output,6,,'output.txt')
while output = input :s(while)
end
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "filecopy" )
@( description, "The job is to create a file called 'output.txt', and place in it" )
@( description, "the contents of the file 'input.txt'." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/File_IO" );
pragma software_model( nonstandard );
pragma license( unrestricted );
procedure filecopy is
begin
if not files.is_readable( "input.txt" ) then
put_line( standard_error, source_info.source_location & ": input file is not readable" );
command_line.set_exit_status( 192 );
return;
end if;
-- With standard shell commands
cp input.txt output.txt;
-- Using built-in capabilities
pragma restriction( no_external_commands );
declare
inputfile : file_type;
outputfile : file_type;
begin
create( outputfile, out_file, "output.txt" );
open( inputfile, in_file, "input.txt" );
while not end_of_file( inputfile ) loop
put_line( outputfile, get_line( inputfile ) );
end loop;
close( inputfile ) @ ( outputfile );
end;
end filecopy;
Standard ML
Reading the whole file at once as a string
(* string -> string -> bool *)
fun copyFile from to =
let
val instream = TextIO.openIn from
val outstream = TextIO.openOut to
val () = TextIO.output (outstream, TextIO.inputAll instream)
val () = TextIO.closeIn instream
val () = TextIO.closeOut outstream
in
true
end handle _ => false
Binary mode using a buffer
fun copyFile from to =
let
val instream = BinIO.openIn from
val outstream = BinIO.openOut to
fun aux () =
let
val buf = BinIO.inputN(instream, 1024)
in
if Word8Vector.length buf = 0
then ()
else (BinIO.output (outstream, buf); aux ())
end
in
(aux (); BinIO.closeIn instream; BinIO.closeOut outstream)
end
Stata
Stata has a copy command. Here is a way to implement this by reading and writing line by line.
program copyfile
file open fin using `1', read text
file open fout using `2', write text replace
file read fin line
while !r(eof) {
file write fout `"`line'"' _newline
file read fin line
}
file close fin
file close fout
end
copyfile input.txt output.txt
Tcl
set in [open "input.txt" r]
set out [open "output.txt" w]
# Obviously, arbitrary transformations could be added to the data at this point
puts -nonewline $out [read $in]
close $in
close $out
For larger files, it is better to use the fcopy command, though in general this restricts what operations can be performed rather more (only encoding and end-of-line translations are possible — or more general byte-level transformations with the generic filter mechanism provided in Tcl 8.6 — none of which are shown here):
set in [open "input.txt" r]
set out [open "output.txt" w]
fcopy $in $out
close $in
close $out
Or the minimal version if we don't need any processing of the data at all:
file copy input.txt output.txt
Other key file I/O operations
- Writing a line to a file:
#open file for writing
set myfile [open "README.TXT" w]
#write something to the file
puts $myfile "This is line 1, so hello world...."
#close the file
close $myfile
- Reading a line from a file:
#open file for reading
set myfile [open "README.TXT" r]
#read something from the file
gets $myfile mydata
#show what was read from the file
#should print "This is line1, so hello world...."
puts $mydata
#close the file
close $myfile
Toka
This is one method, which works with any type of file:
( source dest -- )
{
value| source dest size buffer |
{
{
[ "W" file.open to dest ] is open-dest
[ "R" file.open to source ] is open-source
[ open-dest open-source ]
} is open-files
{
[ source file.size to size ] is obtain-size
[ size malloc to buffer ] is allocate-buffer
[ obtain-size allocate-buffer ]
} is create-buffer
[ source dest and 0 <> ] is check
[ open-files create-buffer check ]
} is prepare
[ source buffer size file.read drop ] is read-source
[ dest buffer size file.write drop ] is write-dest
[ source file.close dest file.close ] is close-files
[ prepare [ read-source write-dest close-files ] ifTrue ]
} is copy-file
And a much simpler way for plain text files, making use of file.slurp:
[ ( source dest -- )
swap file.slurp dup 0 <>
[ >r "W" file.open dup r> string.getLength file.write drop file.close ] ifTrue
] is copy-file
And a test:
" input.txt" " output.txt" copy-file
TUSCRIPT
$$ MODE TUSCRIPT
ERROR/STOP CREATE ("input.txt", seq-o,-std-)
ERROR/STOP CREATE ("output.txt",seq-o,-std-)
FILE/ERASE "input.txt" = "Some irrelevant content"
path2input =FULLNAME(TUSTEP,"input.txt", -std-)
status=READ (path2input,contentinput)
path2output=FULLNAME(TUSTEP,"output.txt",-std-)
status=WRITE(path2output,contentinput)
TXR
As a character string:
(let ((var (file-get-string "input.txt")))
(file-put-string "output.txt" var))
As a list of lines:
(let ((var (file-get-lines "input.txt")))
(file-put-lines "output.txt" var))
UNIX Shell
Using the 'read' built-in
- Hint: mksh(1) manual says, "If read is run in a loop such as while read foo; do ...; done then leading whitespace will be removed (IFS) and backslashes processed. You might want to use while IFS= read -r foo; do ...; done for pristine I/O."
- Caveat: output.txt will end with a newline, whether or not input.txt ended with one.
#!/bin/sh
while IFS= read -r a; do
printf '%s\n' "$a"
done <input.txt >output.txt
Another way, using the 'cat' program
#!/bin/sh
cat input.txt >output.txt
Yet another way, using the 'cp' utility
#!/bin/sh
cp input.txt output.txt
Ursa
decl file input output
decl string contents
input.open "input.txt"
output.create "output.txt"
output.open "output.txt"
set contents (input.readall)
out contents output
Ursala
I/O in Ursala is meant to be handled transparently by the run time system. The application is passed the input files as an argument and expected to return the output files as a result.
Returning a copy of the input file with a new name causes it to be written as a new file.
#import std
#executable ('parameterized','')
fileio = ~command.files; &h.path.&h:= 'output.txt'!
Uxntal
|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
|a0 @File1 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
|b0 @File2 &vector $2 &success $2 &stat $2 &delete $1 &append $1 &name $2 &length $2 &read $2 &write $2
|0100
;in-file .File1/name DEO2
;out-file .File2/name DEO2
&loop
#0100 .File1/length DEO2k POP
;buffer .File1/read DEO2
.File1/success DEI2
.File2/length DEO2k POP
;buffer .File2/write DEO2
EQU2 ?&loop
#80 .System/state DEO
BRK
@in-file "input.txt 00
@out-file "output.txt 00
@buffer $100
Vedit macro language
An edit buffer is normally used as "string variable" in Vedit. To read a file into edit buffer, simply open the file. The file contents can then be modified if required before saving into a new file.
File_Open("input.txt")
File_Save_As("output.txt", NOMSG)
Buf_Close(NOMSG)
Wart
with infile "input.txt"
with outfile "output.txt"
whilet line (read_line)
prn line
Wren
import "io" for File
var contents = File.read("input.txt")
File.create("output.txt") {|file|
file.writeBytes(contents)
}
XPL0
Usage: fileio <input.txt >output.txt
include c:\cxpl\codes;
int I, C;
char IntermediateVariable;
[IntermediateVariable:= GetHp;
I:= 0;
repeat C:= ChIn(1);
IntermediateVariable(I):= C;
I:= I+1;
until C = $1A; \EOF
I:= 0;
repeat C:= IntermediateVariable(I);
I:= I+1;
ChOut(0, C);
until C = $1A; \EOF
]
zkl
var d=File("input.txt").read();
(f:=File("output.txt","w")).write(d); f.close(); // one read, one write copy
File("output.txt").pump(Console); // verify by printing
It might be considered "good form" to immediately close files (rather than wait for the garbage collector to do it) as these are system resources.
var in=File("input.txt"), out=File("output.txt","w");
foreach line in (in) { out.write(line) } // copy line by line
out.close(); // or out=Void and let GC close the file
fin,fout:=File("input.txt","rb"), File("output.txt","wb"); // copy in chunks, implicit buffer
fin.pump(Data(0d524_287),fout); fin.close(); fout.close();
// copy in chunks, let GC close file handles
File("input.txt","rb").pump(Data(0d524_287),File("output.txt","wb"));
In these last two, the implicit buffer (whose size if given by the numbers) is visible inside the pump. Consider this example, which converts input to upper case text on its way to output (the Data() is optional; using it chunks, without, lines):
File("input.txt").pump(Data(),File("output.txt","w"),"text","toUpper");
Zig
Works with: 0.10.x, 0.11.x, 0.12.0-dev.1357+10d03acdb
const std = @import("std");
pub fn main() (error{OutOfMemory} || std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.WriteError)!void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const cwd = std.fs.cwd();
var input_file = try cwd.openFile("input.txt", .{ .mode = .read_only });
defer input_file.close();
var output_file = try cwd.createFile("output.txt", .{});
defer output_file.close();
// Restrict input_file's size to "up to 10 MiB".
var input_file_content = try input_file.readToEndAlloc(allocator, 10 * 1024 * 1024);
defer allocator.free(input_file_content);
try output_file.writeAll(input_file_content);
return;
}
- Programming Tasks
- File handling
- Selection/Short Circuit/Console Program Basics
- Simple
- 11l
- AArch64 Assembly
- ACL2
- Action!
- Action! Tool Kit
- Ada
- Aime
- ALGOL 68
- AppleScript
- ARM Assembly
- Arturo
- AutoHotkey
- AWK
- Babel
- BASIC
- Applesoft BASIC
- BaCon
- BASIC256
- BBC BASIC
- Commodore BASIC
- FreeBASIC
- FutureBasic
- Gambas
- IS-BASIC
- Liberty BASIC
- PureBasic
- QBasic
- QuickBASIC
- RapidQ
- REALbasic
- Run BASIC
- True BASIC
- VBA
- VBScript
- Visual Basic .NET
- Yabasic
- Batch File
- BCPL
- Beef
- Befunge
- BQN
- Bracmat
- C
- C sharp
- C++
- Clean
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- D
- Phobos
- Tango
- DBL
- DCL
- Delphi
- DIBOL-11
- E
- Eiffel
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- Forth
- Fortran
- Frink
- GAP
- GML
- Go
- Groovy
- GUISS
- Haskell
- Hexiscript
- HicEst
- I
- Icon
- Unicon
- IDL
- Io
- J
- Java
- JavaScript
- Jq
- Julia
- K
- Kotlin
- LabVIEW
- Lang
- Lang-io-module
- Lang5
- Lingo
- Lisaac
- Logo
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MAXScript
- Mercury
- MIRC Scripting Language
- Modula-3
- Nanoquery
- NetRexx
- Nim
- Nu
- Objeck
- Object Pascal
- Objective-C
- OCaml
- Octave
- Odin
- Oforth
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- PicoLisp
- Pike
- PL/I
- Pop11
- PowerShell
- Python
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Red
- Retro
- REXX
- Ring
- Ruby
- Rust
- S-BASIC
- Scala
- Scheme
- Seed7
- SenseTalk
- Sidef
- Slate
- Smalltalk
- Snabel
- SNOBOL4
- SparForte
- Standard ML
- Stata
- Tcl
- Toka
- TUSCRIPT
- TXR
- UNIX Shell
- Ursa
- Ursala
- Uxntal
- Vedit macro language
- Wart
- Wren
- XPL0
- Zkl
- Zig
- EasyLang/Omit
- HTML/Omit
- Order/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Unlambda/Omit
- Pages with too many expensive parser function calls