Take notes on the command line: Difference between revisions

From Rosetta Code
Content added Content deleted
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Add SETL)
 
(29 intermediate revisions by 21 users not shown)
Line 1: Line 1:
{{task|Text processing}} {{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]] [[Category:Programming environment operations]]
{{task|Text processing}} {{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]] [[Category:Programming environment operations]]
{{omit from|EasyLang}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Maxima}}
{{omit from|Maxima}}
Line 10: Line 11:
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.


=={{header|11l}}==

<syntaxhighlight lang="11l">:start:
I :argv.len == 1
print(File(‘notes.txt’).read(), end' ‘’)
E
V f = File(‘notes.txt’, APPEND)
f.write(Time().format("YYYY-MM-DD hh:mm:ss\n"))
f.write("\t"(:argv[1..].join(‘ ’))"\n")</syntaxhighlight>

=={{header|8086 Assembly}}==

This code assembles into a .COM file that runs under MS-DOS.

<syntaxhighlight lang="asm"> bits 16
cpu 8086
;;; MS-DOS PSP locations
cmdlen: equ 80h ; Amount of characters on cmdline
cmdtail: equ 82h ; Command line tail
;;; MS-DOS system calls
puts: equ 9h ; Print string to console
date: equ 2Ah ; Get system date
time: equ 2Ch ; Get system time
creat: equ 3Ch ; Create file
open: equ 3Dh ; Open file
close: equ 3Eh ; Close file
read: equ 3Fh ; Read from file
write: equ 40h ; Write to file
lseek: equ 42h ; Set current file position
exit: equ 4ch ; Exit
;;; File modes
O_RDONLY: equ 0
O_WRONLY: equ 1
;;; Error codes (well, we only need the one)
ENOTFOUND: equ 2
;;; File positions (again we need only the one)
FP_END: equ 2
;;; File buffer size
BUFSZ: equ 4096
section .text
org 100h
cmp byte [cmdlen],0 ; Is the command line empty?
je printnotes ; Then, go print current notes
;;; Retrieve and format current date and time
mov ah,date ; Retrieve date
int 21h
mov di,datefmt ; Fill in date string
xor ah,ah
mov al,dh ; Write month
mov bl,2 ; Two digits
call asciinum
add di,3 ; Onwards three positions
mov al,dl ; Write day
mov bl,2 ; Two digits
call asciinum
add di,3 ; Onwards three positions
mov ax,cx ; Write year
mov bl,4 ; Four digits
call asciinum
mov ah,time ; Get system time
int 21h
mov di,timefmt+6 ; Fill in time string
xor ah,ah
mov al,dh ; Write seconds
mov bl,2 ; Two digits
call asciinum
sub di,3 ; Back three positions
mov al,cl ; Write minutes
mov bl,2 ; Two digits
call asciinum
cmp ch,12 ; AM or PM?
jbe houram ; <=12, AM
sub ch,12 ; PM - subtract 12 hours,
mov byte [ampm],'P' ; And set the AM/PM to 'P'(M)
jmp wrhours
houram: and ch,ch ; Hour 0 is 12:XX:XX AM.
jnz wrhours
mov ch,12
wrhours: sub di,3 ; Back three positions
mov al,ch ; Write hours
mov bl,2 ; Two digits
call asciinum
;;; Open or create the NOTES.TXT file
mov dx,filnam
mov ax,open<<8|O_WRONLY
int 21h ; Try to open the file
jnc writenote ; If successful, go write the note
cmp al,ENOTFOUND ; File not found?
jne diefile ; Some other error = print error msg
mov ah,creat ; No notes file, try to create it
xor cx,cx ; Normal file (no attributes set)
int 21h
jc diefile ; If that fails too, print error msg
;;; Write the note to the file
writenote: mov bx,ax ; File handle in BX
mov ax,lseek<<8|FP_END ; Seek to end of file
xor cx,cx ; Offset 0
xor dx,dx
int 21h
jc diefile ; Error if it fails
mov dx,datetime ; Write the date/time string first
mov cx,dtsize
mov ah,write
int 21h
jc diefile ; Error if it fails
mov cx,bx ; Store file handle in CX
;;; Terminate note with \r\n
xor bx,bx ; BX = length of command line
mov bl,[cmdlen] ; Find 2 bytes past cmd input
add bx,cmdlen+1 ; Note: this might overwrite the first
mov word [bx],0A0Dh ; instruction, but we don't need it
sub bx,cmdtail-2 ; Get length (add 2 for the 0D0A)
xchg bx,cx ; File handle in BX, length in CX
mov dx,cmdtail ; Write what's on the command line
mov ah,write
int 21h
jc diefile ; Error if it fails.
jmp closeexit ; Close file and exit if it succeeds.
;;; Print the contents of the NOTES.TXT file
printnotes: mov dx,filnam ; Open file for reading
mov ax,open<<8|O_RDONLY
int 21h
jnc readnotes ; Carry flag set = error.
cmp al,ENOTFOUND ; File not found?
jne diefile ; Some other error = print error msg
jmp exitok ; Not found = no notes = just exit
readnotes: mov di,ax ; Keep the file handle in DI.
.loop mov bx,di ; Get file handle for file
mov cx,BUFSZ ; Read as many bytes as will fit in the
mov ah,read ; buffer
int 21h
jc diefile ; Carry flag set = error
and ax,ax ; If 0 bytes read, we're done.
jz .done
xor bx,bx ; File handle 0 = standard output
mov cx,ax ; Write as many bytes as we read
mov ah,write
int 21h
jc diefile
jmp .loop ; Go get more bytes if there are any
.done mov bx,di ; Done: close the file
closeexit: mov ah,close
int 21h
exitok: mov ax,exit<<8|0 ; Exit with errorlevel 0 (success)
int 21h
;;; Print 'File error' and exit.
diefile: mov dx,fileerror
;;; Print error message in DX and exit
die: mov ah,puts ; Print error message
int 21h
mov ax,exit<<8|2 ; Exit with errorlevel 2.
int 21h
;;; Subroutine: write AX as BL-digit ASCII number at [DI]
asciinum: push dx ; Store DX and CX
push cx
mov cx,10 ; CX = divisor
xor bh,bh ; We never need >255.
.loop: xor dx,dx ; Set high word of division to 0.
div cx ; AX /= CX; DX = AX % CX
add dl,'0' ; Make digit ASCII
dec bl ; Move forward one digit
mov [di+bx],dl ; Store digit
jnz .loop ; Are we there yet?
pop cx ; Restore DX and CX
pop dx
ret
section .data
datetime: equ $ ; Start of date/time string.
datefmt: db '**/**/**** ' ; Date placeholder,
timefmt: db '**:**:** ' ; Time placeholder,
ampm: db 'AM' ; AM/PM placeholder.
db 13,10,9 ; \r\n\t
dtsize: equ $-datetime ; Size of date/time string.
fileerror: db 'File error.$' ; Printed on error
filnam: db 'NOTES.TXT',0 ; File name to use
section .bss
filebuf: resb BUFSZ ; 4K file buffer</syntaxhighlight>

{{out}}
<pre>A:\>dir/b notes.*
NOTES.COM

A:\>notes

A:\>notes This is a note.

A:\>notes This is another note.

A:\>notes
05/11/2020 07:52:34 PM
This is a note.
05/11/2020 07:52:38 PM
This is another note.

A:\>dir/b notes.*
NOTES.COM
NOTES.TXT

A:\></pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program notes64.s */

/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 10000
.equ O_APPEND, 0x400
.equ GETTIME, 0xa9 // call system linux gettimeofday

/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: //
.struct timeval_sec + 8
timeval_usec: //
.struct timeval_usec + 8
timeval_end:
.struct 0
timezone_min: //
.struct timezone_min + 8
timezone_dsttime: //
.struct timezone_dsttime + 8
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szSpace: .asciz " "
szLibNoFile: .asciz "no file notes.txt in this directory\n"
szFileName: .asciz "notes.txt"
szMessAnoRead: .asciz "Error read file \n"
szMessAnoTime: .asciz "Error call time \n"
szMessAnoWrite: .asciz "Error file write \n"
szMessDate: .asciz " @/@/@ @:@:@ \n" // message time
.align 8
tbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov fp,sp // stack address
ldr x20,[fp] // load number of parameters command line
cmp x20,#1 // >1 insertion text
bgt 10f
mov x0,AT_FDCWD
ldr x1,qAdrszFileName // file name
mov x2,#O_RDONLY // flags
mov x3,#0 // mode in octal
mov x8,#OPEN // open file, create if not exist
svc 0
cmp x0,#0 // error open
ble 99f // file no exists ?
mov x19,x0 // save FD and if file exist display text
ldr x1,qAdrsBuffer // buffer address
ldr x2,#iBufferSize // buffersize
mov x8,READ
svc 0
cmp x0,#0 // error read ?
blt 98f
ldr x0,qAdrsBuffer // buffer address
bl affichageMess // and display
b 50f
10: // multiple parameters in command line
mov x0,AT_FDCWD
ldr x1,qAdrszFileName // file name
ldr x2,iFlag // flags
mov x3,#0644 // mode in octal
mov x8,#OPEN // open file, create if not exist
svc 0
cmp x0,#0 // error open
ble 96f
mov x19,x0 // save FD
ldr x0,qAdrstTVal
ldr x1,qAdrstTZone
mov x8,#GETTIME // call system function time
svc 0
cmp x0,#-1 // error ?
beq 97f
ldr x1,qAdrstTVal
ldr x0,[x1,timeval_sec] // timestamp in second
bl formatTime // format date and hour
mov x1,x0
mov x2,#0
11: // compute length of time message
ldrb w3,[x1,x2]
cmp w3,#0
beq 12f
add x2,x2,#1
b 11b
12:
mov x0,x19 // write time message
mov x8,#WRITE
svc 0
cmp x0,#0 // error ?
ble 96f
mov x5,#2 // start parameters command line
13:
mov x0,x19 // file FD
ldr x1,[fp,x5,lsl #3] // load parameter address
mov x2,#0
14: // compute parameter length
ldrb w3,[x1,x2]
cmp w3,#0
beq 15f
add x2,x2,#1
b 14b
15: // write parameter
mov x8,#WRITE
svc 0
cmp x0,#0 // error ?
ble 96f
mov x0,x19 // file FD
ldr x1,iadrszSpace // write a space betwin parameters
mov x2,#1
mov x8,#WRITE
svc 0
add x5,x5,#1 // increment indixe
cmp x5,x20 // parameters maxi ?
ble 13b // no -> loop
mov x0,x19
ldr x1,qAdrszCarriageReturn // write line end
mov x2,#1
mov x7,#WRITE
svc 0

50: // close the file
mov x0,x19
mov x8,CLOSE
svc 0
b 100f

96: // error write
ldr x0,qAdrszMessAnoWrite
bl affichageMess
b 100f
97: // error function time
ldr x0,qAdrszMessAnoTime
bl affichageMess
b 100f
98: // error read
ldr x0,qAdrszMessAnoRead
bl affichageMess
b 100f
99: // display message no file in this directory
ldr x0,qAdrszLibNoFile
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszFileName: .quad szFileName
qAdrszLibNoFile: .quad szLibNoFile
qAdrsBuffer: .quad sBuffer
iBufferSize: .quad BUFFERSIZE
qAdrszMessAnoRead: .quad szMessAnoRead
qAdrszMessAnoTime: .quad szMessAnoTime
qAdrszMessAnoWrite: .quad szMessAnoWrite
iFlag: .quad O_RDWR|O_APPEND|O_CREAT
qAdrstTVal: .quad stTVal
qAdrstTZone: .quad stTZone
iadrszSpace: .quad szSpace
/***************************************************/
/* formatting time area */
/***************************************************/
// x0 contains time area
// x0 return address result string
formatTime:
stp x2,lr,[sp,-16]! // save registers
ldr x2,qSecJan2020
sub x3,x0,x2 // total secondes to 01/01/2020
mov x4,60
udiv x5,x3,x4
msub x6,x5,x4,x3 // compute secondes
udiv x3,x5,x4
msub x7,x3,x4,x5 // compute minutes
mov x4,24
udiv x5,x3,x4
msub x8,x5,x4,x3 // compute hours
mov x4,(365 * 4 + 1)
udiv x9,x5,x4
lsl x9,x9,2 // multiply by 4 = year1
udiv x12,x5,x4
msub x10,x12,x4,x5
ldr x11,qAdrtbDayMonthYear
mov x12,3
mov x13,12
1:
mul x14,x13,x12
ldr x15,[x11,x14,lsl 3] // load days by year
cmp x10,x15
bge 2f
sub x12,x12,1
cmp x12,0
cbnz x12,1b
2: // x12 = year2
mov x16,11
mul x15,x13,x12
lsl x15,x15,3 // * par 8
add x14,x15,x11
3:
ldr x15,[x14,x16,lsl 3] // load days by month
cmp x10,x15
bge 4f
sub x16,x16,1
cmp x16,0
cbnz x16,3b
4: // x16 = month - 1
mul x15,x13,x12
add x15,x15,x16
ldr x1,qAdrtbDayMonthYear
ldr x3,[x1,x15,lsl 3]
sub x0,x10,x3
add x0,x0,1 // final compute day
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessDate
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first @ character
mov x2,x0
add x0,x16,1 // final compute month
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
add x0,x9,2020
add x0,x0,x12 // final compute year = 2020 + year1 + year2
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x8 // hours
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x7 // minutes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x6 // secondes
ldr x1,qAdrsZoneConv
bl conversion10
mov x4,#0 // store zero final
strb w4,[x1,x0]
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next // character
100:
ldp x2,lr,[sp],16 // restaur registers
ret
qAdrszMessDate: .quad szMessDate
qSecJan2020: .quad 1577836800
qAdrtbDayMonthYear: .quad tbDayMonthYear

/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
</syntaxhighlight>
{{output}}
<pre>
~/.../rosetta/asm3 $ notes64
11/4/2023 15:16:29
initialisation
11/4/2023 15:16:45
verification
11/4/2023 15:17:15
suite modification revoir le cas

</pre>
=={{header|Ada}}==
=={{header|Ada}}==
{{works with|Ada 2005}}
{{works with|Ada 2005}}


<lang Ada>with Ada.Calendar.Formatting;
<syntaxhighlight lang="ada">with Ada.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Command_Line;
Line 63: Line 567:
Ada.Text_IO.Close (File => Notes_File);
Ada.Text_IO.Close (File => Notes_File);
end if;
end if;
end Notes;</lang>
end Notes;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>#! /usr/local/bin/aime -a
<syntaxhighlight lang="aime">#! /usr/local/bin/aime -a


if (argc() == 1) {
if (argc() == 1) {
Line 93: Line 597:


f.byte('\n');
f.byte('\n');
}</lang>
}</syntaxhighlight>

=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
/*
Take notes on the command line. Rosettacode.org
*/
#include <basico.h>

algoritmo
cuando ' no existe el archivo ("NOTES.txt") ' {
sys = `touch NOTES.txt`; luego limpiar 'sys'
}
si ' total argumentos es (1) '
cargar cadena desde ("NOTES.txt"); luego imprime
sino
msg=""; obtener todos los parámetros, guardar en 'msg'
#( msg = strtran("@","\n\t",msg) )
fijar separador 'NULO'
fecha y hora, "\n\t", msg, "\n\n", unir esto;
añadir al final de ("NOTES.txt")
fin si
terminar
</syntaxhighlight>
{{out}}
<pre>
:
:
$ hopper3 basica/notes.bas otra y otra y otra...@y otra
$ hopper3 basica/notes.bas
27/11/2023,23:38:28:74
iniciando estas notas con un mensaje
de prueba

27/11/2023,23:40:57:41
nota 2:
establecer parámetro

27/11/2023,23:52:22:82
nueva nota de prueba
ta es medianoche

27/11/2023,23:55:07:20
otra nueva nota

27/11/2023,23:56:21:15
otra y otra y otra...
y otra

$ hopper3 basica/notes.bas borrar todo de este directorio@sin asco
$ hopper3 basica/notes.bas
27/11/2023,23:38:28:74
iniciando estas notas con un mensaje
de prueba

27/11/2023,23:40:57:41
nota 2:
establecer parámetro

27/11/2023,23:52:22:82
nueva nota de prueba
ta es medianoche

27/11/2023,23:55:07:20
otra nueva nota

27/11/2023,23:56:21:15
otra y otra y otra...
y otra

28/11/2023,00:04:04:62
borrar todo de este directorio
sin asco

$
</pre>

=={{header|APL}}==
{{works with|GNU APL}}

<syntaxhighlight lang="apl">#!/usr/local/bin/apl -s --

∇r←ch Join ls ⍝ Join list of strings with character
r←1↓∊ch,¨ls

∇d←Date ⍝ Get system date as formatted string
d←'/'Join ⍕¨1⌽3↑⎕TS

∇t←Time;t24 ⍝ Get system time as formatted string
t←t24←3↑3↓⎕TS ⍝ Get system time
t[1]←t[1]-12×t24[1]≥12 ⍝ If PM (hour≥12), subtract 12 from hour
t[1]←t[1]+12×t[1]=0 ⍝ Hour 0 is hour 12 (AM)
t←¯2↑¨'0',¨⍕¨t ⍝ Convert numbers to 2-digit strings
t←(':'Join t),(1+t24[1]≥12)⊃' AM' ' PM' ⍝ Add AM/PM and ':' separator

∇Read;f
→(¯2≡f←⎕FIO[49]'notes.txt')/0 ⍝ Read file, stop if not found
⎕←⊃f ⍝ Output file line by line

∇Write note;f;_
note←' 'Join note ⍝ flatten input and separate with spaces
note←Date,' ',Time,(⎕UCS 10 9),note,⎕UCS 10 ⍝ note format
f←'a'⎕FIO[3]'notes.txt' ⍝ append to file
_←(⎕UCS note)⎕FIO[7]f ⍝ write note to end of file
_←⎕FIO[4]f ⍝ close the file

∇Notes;note
⍎∊('Read' 'Write note')[1+0≠⍴note←4↓⎕ARG]

Notes
)OFF</syntaxhighlight>

{{out}}
<pre>$ ls notes.*
notes.apl
$ ./notes.apl

$ ./notes.apl This is a test

$ ./notes.apl This is another test

$ ./notes.apl Note that this is a test

$ ./notes.apl
5/11/2020 09:33:14 PM
This is a test
5/11/2020 09:33:18 PM
This is another test
5/11/2020 09:33:36 PM
Note that this is a test

$ ls notes.*
notes.apl notes.txt</pre>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Requires a modernish version of OS X (Lion or later) on which osascript works as a shebang interpreter.
Requires a modernish version of OS X (Lion or later) on which osascript works as a shebang interpreter.
<lang applescript>#!/usr/bin/osascript
<syntaxhighlight lang="applescript">#!/usr/bin/osascript


-- format a number as a string with leading zero if needed
-- format a number as a string with leading zero if needed
Line 179: Line 823:
end try
end try
end if
end if
end run</lang>
end run</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI or android 32 bits */
/* program notes.s */

/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ BUFFERSIZE, 10000
.equ READ, 3 @ system call
.equ WRITE, 4 @ Linux syscall
.equ OPEN, 5 @ system call
.equ CLOSE, 6 @ system call
.equ O_RDONLY, 0
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ O_APPEND, 0x400
.equ O_CREAT, 0x40
.equ GETTIME, 0x4e @ call system linux gettimeofday


/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: @
.struct timeval_sec + 4
timeval_usec: @
.struct timeval_usec + 4
timeval_end:
.struct 0
timezone_min: @
.struct timezone_min + 4
timezone_dsttime: @
.struct timezone_dsttime + 4
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szSpace: .asciz " "
szLibNoFile: .asciz "no file notes.txt in this directory\n"
szFileName: .asciz "notes.txt"
szMessAnoRead: .asciz "Error read file \n"
szMessAnoTime: .asciz "Error call time \n"
szMessAnoWrite: .asciz "Error file write \n"
szMessDate: .asciz " @/@/@ @:@:@ \n" @ message time
.align 4
tbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov fp,sp @ stack address
ldr r4,[fp] @ load number of parameters command line
cmp r4,#1 @ >1 insertion text
bgt 10f
ldr r0,iAdrszFileName @ file name
mov r1,#O_RDONLY @ flags
mov r2,#0 @ mode in octal
mov r7,#OPEN @ oen file, create if not exist
svc 0
cmp r0,#0 @ error open
ble 99f @ file no exists ?
mov r8,r0 @ save FD @ if exist display text
ldr r1,iAdrsBuffer @ buffer address
ldr r2,#iBufferSize @ buffersize
mov r7, #READ @ read file
svc 0
cmp r0,#0 @ error read ?
blt 98f
ldr r0,iAdrsBuffer @ buffer address
bl affichageMess @ and display
b 50f
10: @ multiple parameters in command line
ldr r0,iAdrszFileName @ file name
ldr r1,iFlag @ flags
mov r2,#0644 @ mode in octal
mov r7,#OPEN @ open file, create if not exist
svc 0
cmp r0,#0 @ error open
ble 96f
mov r8,r0 @ save FD
ldr r0,iAdrstTVal
ldr r1,iAdrstTZone
mov r7,#GETTIME @ call system function time
svc 0
cmp r0,#-1 @ error ?
beq 97f
ldr r0,iAdrstTVal
bl formatTime @ format date and hour
mov r1,r0
mov r2,#0
11: @ compute length of time message
ldrb r3,[r1,r2]
cmp r3,#0
beq 12f
add r2,#1
b 11b
12:
mov r0,r8 @ write time message
mov r7,#WRITE
svc 0
cmp r0,#0 @ error ?
ble 96f
mov r5,#2 @ start parameters command line
13:
mov r0,r8 @ file FD
ldr r1,[fp,r5,lsl #2] @ load parameter address
mov r2,#0
14: @ compute parameter length
ldrb r3,[r1,r2]
cmp r3,#0
beq 15f
add r2,#1
b 14b
15: @ write parameter
mov r7,#WRITE
svc 0
cmp r0,#0 @ error ?
ble 96f
mov r0,r8 @ file FD
ldr r1,iadrszSpace @ write a space betwin parameters
mov r2,#1
mov r7,#WRITE
svc 0
add r5,#1 @ increment indixe
cmp r5,r4 @ parameters maxi ?
ble 13b @ no -> loop
mov r0,r8
ldr r1,iAdrszCarriageReturn @ write line end
mov r2,#1
mov r7,#WRITE
svc 0

50: @ close the file
mov r0,r8
mov r7, #CLOSE
svc 0
b 100f

96: @ error write
ldr r0,iAdrszMessAnoWrite
bl affichageMess
b 100f
97: @ error function time
ldr r0,iAdrszMessAnoTime
bl affichageMess
b 100f
98: @ error read
ldr r0,iAdrszMessAnoRead
bl affichageMess
b 100f
99: @ display message no file in this directory
ldr r0,iAdrszLibNoFile
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszFileName: .int szFileName
iAdrszLibNoFile: .int szLibNoFile
iAdrsBuffer: .int sBuffer
iBufferSize: .int BUFFERSIZE
iAdrszMessAnoRead: .int szMessAnoRead
iAdrszMessAnoTime: .int szMessAnoTime
iAdrszMessAnoWrite: .int szMessAnoWrite
iFlag: .int O_RDWR|O_APPEND|O_CREAT
iAdrstTVal: .int stTVal
iAdrstTZone: .int stTZone
iadrszSpace: .int szSpace
/***************************************************/
/* formatting time area */
/***************************************************/
// r0 contains time area
// r0 return address result string
formatTime:
push {r2-r12,lr} @ save registers
ldr r1,[r0,#timeval_sec] @ timestemp in second
ldr r2,iSecJan2020
sub r0,r1,r2 @ total secondes to 01/01/2020
mov r1,#60
bl division
mov r0,r2
mov r6,r3 @ compute secondes
mov r1,#60
bl division
mov r7,r3 @ compute minutes
mov r0,r2
mov r1,#24
bl division
mov r8,r3 @ compute hours
mov r0,r2
mov r11,r0
mov r1,#(365 * 4 + 1)
bl division
lsl r9,r2,#2 @ multiply by 4 = year1
mov r1,#(365 * 4 + 1)
mov r0,r11
bl division
mov r10,r3
ldr r1,iAdrtbDayMonthYear
mov r2,#3
mov r3,#12
1:
mul r11,r3,r2
ldr r12,[r1,r11,lsl #2] @ load days by year
cmp r10,r12
bge 2f
sub r2,r2,#1
cmp r2,#0
bne 1b
2: @ r2 = year2
mov r5,#11
mul r4,r3,r2
lsl r4,#2
add r4,r1
3:
ldr r12,[r4,r5,lsl #2] @ load days by month
cmp r10,r12
bge 4f
subs r5,r5,#1
bne 3b
4: @ r5 = month - 1
mul r11,r3,r2
add r11,r5
ldr r1,iAdrtbDayMonthYear
ldr r3,[r1,r11,lsl #2]
sub r0,r10,r3

add r0,r0,#1 @ final compute day
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r4,#0 @ store zero final
strb r4,[r1,r0]
ldr r0,iAdrszMessDate
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
add r0,r5,#1 @ final compute month
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r11,iYearStart
add r0,r9,r11
add r0,r0,r2 @ final compute year = 2020 + year1 + year2
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r8 @ hours
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r7 @ minutes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r6 @ secondes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character

100:
pop {r2-r12,pc} @ restaur registers
iAdrszMessDate: .int szMessDate
iSecJan2020: .int 1577836800
iAdrtbDayMonthYear: .int tbDayMonthYear
iYearStart: .int 2020

/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
~/.../rosetta/asm3 $ notes
10/4/2023 19:32:34
creation fichier notes
10/4/2023 19:32:53
affichage fichier
~/.../rosetta/asm3 $ notes saisie des exemples
~/.../rosetta/asm3 $ notes
10/4/2023 19:32:34
creation fichier notes
10/4/2023 19:32:53
affichage fichier
10/4/2023 19:37:58
saisie des exemples
</pre>
=={{header|Arturo}}==

<syntaxhighlight lang="rebol">notes: "notes.txt"
if? empty? arg [
if exists? notes -> print read notes
]
else [
output: (to :string now) ++ "\n" ++
"\t" ++ (join.with:" " to [:string] arg) ++ "\n"
write.append notes output
]</syntaxhighlight>

{{out}}

Example <code>notes.txt</code>:
<pre>2021-06-03T07:17:21+02:00
this is a note
2021-06-03T07:17:26+02:00
this is another note</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>Notes := "Notes.txt"
<syntaxhighlight lang="autohotkey">Notes := "Notes.txt"


If 0 = 0 ; no arguments
If 0 = 0 ; no arguments
Line 204: Line 1,205:
FileAppend, `r`n, %Notes%
FileAppend, `r`n, %Notes%


EOF:</lang>
EOF:</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ]
# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ]
# examples:
# examples:
Line 232: Line 1,233:
printf("\n") >>log_name
printf("\n") >>log_name
}
}
</syntaxhighlight>
</lang>
{{out}} from the three example commands:
{{out}} from the three example commands:
<pre>
<pre>
Line 247: Line 1,248:
for this to work with older versions of QB.
for this to work with older versions of QB.


<lang qbasic>IF LEN(COMMAND$) THEN
<syntaxhighlight lang="qbasic">IF LEN(COMMAND$) THEN
OPEN "notes.txt" FOR APPEND AS 1
OPEN "notes.txt" FOR APPEND AS 1
PRINT #1, DATE$, TIME$
PRINT #1, DATE$, TIME$
Line 262: Line 1,263:
CLOSE
CLOSE
END IF
END IF
END IF</lang>
END IF</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
{{works with|Windows NT|4}}
{{works with|Windows NT|4}}
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
if %1@==@ (
if %1@==@ (
if exist notes.txt more notes.txt
if exist notes.txt more notes.txt
Line 272: Line 1,273:
)
)
echo %date% %time%:>>notes.txt
echo %date% %time%:>>notes.txt
echo %*>>notes.txt</lang>
echo %*>>notes.txt</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
This must be compiled to an EXE and run from the command prompt.
This must be compiled to an EXE and run from the command prompt.
<lang bbcbasic> REM!Exefile C:\NOTES.EXE, encrypt, console
<syntaxhighlight lang="bbcbasic"> REM!Exefile C:\NOTES.EXE, encrypt, console
REM!Embed
REM!Embed
LF = 10
LF = 10
Line 305: Line 1,306:
CLOSE #notes%
CLOSE #notes%
QUIT</lang>
QUIT</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <time.h>
#include <time.h>


Line 338: Line 1,339:
if (note) fclose(note);
if (note) fclose(note);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.IO;
using System.IO;
using System.Text;
using System.Text;
Line 373: Line 1,374:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <fstream>
<syntaxhighlight lang="cpp">#include <fstream>
#include <iostream>
#include <iostream>
#include <ctime>
#include <ctime>
Line 412: Line 1,413:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(ns rosettacode.notes
<syntaxhighlight lang="clojure">(ns rosettacode.notes
(:use [clojure.string :only [join]]))
(:use [clojure.string :only [join]]))


Line 427: Line 1,428:
(println (slurp "NOTES.txt"))))
(println (slurp "NOTES.txt"))))


(notes *command-line-args*)</lang>
(notes *command-line-args*)</syntaxhighlight>


{{out}}
{{out}}
Line 445: Line 1,446:


</pre>
</pre>

=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program uses the "get_argv" function that is supplied iwth
% PCLU in "useful.lib".

NOTEFILE = "notes.txt"

% Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM]
format_date = proc (d: date) returns (string)
ds: stream := stream$create_output()
stream$putzero(ds, int$unparse(d.month), 2)
stream$putc(ds, '/')
stream$putzero(ds, int$unparse(d.day), 2)
stream$putc(ds, '/')
stream$putzero(ds, int$unparse(d.year), 4)
stream$putc(ds, ' ')
hour: int := d.hour // 12
if hour=0 then hour:=12 end
ampm: string := "AM"
if d.hour>=12 then ampm := "PM" end
stream$putzero(ds, int$unparse(hour), 2)
stream$putc(ds, ':')
stream$putzero(ds, int$unparse(d.minute), 2)
stream$putc(ds, ':')
stream$putzero(ds, int$unparse(d.second), 2)
stream$putc(ds, ' ')
stream$puts(ds, ampm)
return(stream$get_contents(ds))
end format_date

% Add a note to the file
add_note = proc (note: sequence[string])
fn: file_name := file_name$parse(NOTEFILE)
out: stream := stream$open(fn, "append")
stream$putl(out, format_date(now()))
c: char := '\t'
for part: string in sequence[string]$elements(note) do
stream$putc(out, c)
stream$puts(out, part)
c := ' '
end
stream$putc(out, '\n')
stream$close(out)
end add_note

% Show the notes file, if it exists
show_notes = proc ()
po: stream := stream$primary_output()
fn: file_name := file_name$parse(NOTEFILE)
begin
inp: stream := stream$open(fn, "read")
while true do
stream$putl(po, stream$getl(inp))
except when end_of_file: break end
end
stream$close(inp)
end except when not_possible(s: string): end
end show_notes

% Add a note if one is given, show the notes otherwise
start_up = proc ()
note: sequence[string] := get_argv()
if sequence[string]$empty(note)
then show_notes()
else add_note(note)
end
end start_up</syntaxhighlight>
{{out}}
<pre>$ ls
notes
$ ./notes

$ ./notes This is a test
$ ./notes This is another test
$ ./notes Note that this is a test
$ ./notes
12/15/2021 11:18:50 AM
This is a test
12/15/2021 11:18:52 AM
This is another test
12/15/2021 11:19:00 AM
Note that this is a test

$ ls
notes notes.txt</pre>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. NOTES.
PROGRAM-ID. NOTES.


Line 525: Line 1,614:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defparameter *notes* "NOTES.TXT")
<syntaxhighlight lang="lisp">(defparameter *notes* "NOTES.TXT")


(defun format-date-time (stream)
(defun format-date-time (stream)
Line 549: Line 1,638:


(defun main ()
(defun main ()
(notes (uiop:command-line-arguments)))</lang>
(notes (uiop:command-line-arguments)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main(in string[] args) {
<syntaxhighlight lang="d">void main(in string[] args) {
import std.stdio, std.file, std.datetime, std.range;
import std.stdio, std.file, std.datetime, std.range;


Line 565: Line 1,654:
f.writefln("\t%-(%s %)", args.dropOne);
f.writefln("\t%-(%s %)", args.dropOne);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>C:\>notes Permission to speak, sir!
<pre>C:\>notes Permission to speak, sir!
Line 579: Line 1,668:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>program notes;
<syntaxhighlight lang="delphi">program notes;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 620: Line 1,709:
sw.Free;
sw.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e>#!/usr/bin/env rune
<syntaxhighlight lang="e">#!/usr/bin/env rune


def f := <file:notes.txt>
def f := <file:notes.txt>
Line 640: Line 1,729:
w.close()
w.close()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Take_notes do
<syntaxhighlight lang="elixir">defmodule Take_notes do
@filename "NOTES.TXT"
@filename "NOTES.TXT"
Line 658: Line 1,747:
end
end


Take_notes.main(System.argv)</lang>
Take_notes.main(System.argv)</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
#! /usr/bin/env escript
#! /usr/bin/env escript


Line 686: Line 1,775:
Existing_contents = file_contents(),
Existing_contents = file_contents(),
file:write_file( file(), [Existing_contents, Notes, "\n"] ).
file:write_file( file(), [Existing_contents, Notes, "\n"] ).
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>constant cmd = command_line()
<syntaxhighlight lang="euphoria">constant cmd = command_line()
constant filename = "notes.txt"
constant filename = "notes.txt"
integer fn
integer fn
Line 720: Line 1,809:
puts(fn,line)
puts(fn,line)
close(fn)
close(fn)
end if</lang>
end if</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>open System;;
<syntaxhighlight lang="fsharp">open System;;
open System.IO;;
open System.IO;;


Line 745: Line 1,834:
| 0 -> show_notes()
| 0 -> show_notes()
| _ -> take_note <| String.concat " " args;
| _ -> take_note <| String.concat " " args;
0;;</lang>
0;;</syntaxhighlight>


Usage:
Usage:
Line 762: Line 1,851:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>#! /usr/bin/env factor
<syntaxhighlight lang="factor">#! /usr/bin/env factor
USING: kernel calendar calendar.format io io.encodings.utf8 io.files
USING: kernel calendar calendar.format io io.encodings.utf8 io.files
sequences command-line namespaces ;
sequences command-line namespaces ;
Line 774: Line 1,863:
print flush
print flush
] with-file-appender
] with-file-appender
] if-empty</lang>
] if-empty</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Notes
class Notes
{
{
Line 804: Line 1,893:
}
}
}
}
</syntaxhighlight>
</lang>


Sample:
Sample:
Line 824: Line 1,913:
The following is SwiftForth-specific, and runs in the Forth environment rather than as a standalone terminal application. Win32Forth only needs simple replacements of DATE and TIME . A Unix Forth would come closer to the 'commandline' requirement, as Windows Forths for whatever reason very eagerly discard the Windows console. Because this runs in the Forth environment, the otherwise acceptable application words are stuffed in a wordlist. Standard Forth doesn't have the notion of create-it-if-it-doesn't-exist, so OPEN just tries again with CREATE-FILE if OPEN-FILE fails.
The following is SwiftForth-specific, and runs in the Forth environment rather than as a standalone terminal application. Win32Forth only needs simple replacements of DATE and TIME . A Unix Forth would come closer to the 'commandline' requirement, as Windows Forths for whatever reason very eagerly discard the Windows console. Because this runs in the Forth environment, the otherwise acceptable application words are stuffed in a wordlist. Standard Forth doesn't have the notion of create-it-if-it-doesn't-exist, so OPEN just tries again with CREATE-FILE if OPEN-FILE fails.


<lang forth>vocabulary note-words
<syntaxhighlight lang="forth">vocabulary note-words
get-current also note-words definitions
get-current also note-words definitions


Line 867: Line 1,956:
open 0 parse dup if add-note
open 0 parse dup if add-note
else 2drop dump then close ;
else 2drop dump then close ;
previous</lang>
previous</syntaxhighlight>
The following is exactly the same program, but written in 4tH. 4tH has an I/O system which is different from ANS-Forth. The notes file is specified on the commandline.
The following is exactly the same program, but written in 4tH. 4tH has an I/O system which is different from ANS-Forth. The notes file is specified on the commandline.
<lang forth>\ -- notes.txt
<syntaxhighlight lang="forth">\ -- notes.txt
include lib/argopen.4th
include lib/argopen.4th
include lib/ansfacil.4th
include lib/ansfacil.4th
Line 897: Line 1,986:
refill drop 0 parse dup if add-note else 2drop dump then ;
refill drop 0 parse dup if add-note else 2drop dump then ;


note</lang>
note</syntaxhighlight>

=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
program notes
implicit none
integer :: i, length, iargs, lun, ios
integer,dimension(8) :: values
character(len=:),allocatable :: arg
character(len=256) :: line
character(len=1),parameter :: tab=char(9)
iargs = command_argument_count()
open(file='notes.txt',newunit=lun,action='readwrite',position='append',status='unknown')
if(iargs.eq.0)then
rewind(lun)
do
read(lun,'(a)',iostat=ios)line
if(ios.ne.0)exit
write(*,'(a)')trim(line)
enddo
else
call date_and_time(VALUES=values)
write(lun,'(*(g0))')values(1),"-",values(2),"-",values(3),"T",values(5),":",values(6),":",values(7)
write(lun,'(a)',advance='no')tab
do i=1,iargs
call get_command_argument(number=i,length=length)
arg=repeat(' ',length)
call get_command_argument(i, arg)
write(lun,'(a,1x)',advance='no')arg
enddo
write(lun,*)
endif
end program notes
</syntaxhighlight>
{{out}}<pre>
2022-2-20T18:40:13
this is an initial note
2022-2-20T18:40:38
the note of the day
</pre>

=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">If Len(Command) Then
Open "notes.txt" For Append As #1
Print #1, Date, Time
Print #1, Chr(9); Command
Close
Else
If Open("notes.txt" For Input As #1) = 0 Then
Dim As String lin
Print "Contenido del archivo:"
Do While Not Eof(1)
Line Input #1, lin
Print lin
Loop
Else
Open "notes.txt" For Output As #1
Print "Archivo 'NOTES.TXT' creado"
End If
End If
Close #1
Sleep</syntaxhighlight>



=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'
<syntaxhighlight lang="gambas">'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'


Public Sub Main()
Public Sub Main()
Line 922: Line 2,073:
Endif
Endif


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 932: Line 2,083:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 980: Line 2,131:
os.Exit(1)
os.Exit(1)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def notes = new File('./notes.txt')
<syntaxhighlight lang="groovy">def notes = new File('./notes.txt')
if (args) {
if (args) {
notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
Line 989: Line 2,140:
println notes.text
println notes.text
}
}
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.Environment (getArgs)
<syntaxhighlight lang="haskell">import System.Environment (getArgs)
import System.Time (getClockTime)
import System.Time (getClockTime)


Line 1,003: Line 2,154:
else
else
do ct <- getClockTime
do ct <- getClockTime
appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n"</lang>
appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n"</syntaxhighlight>


{{out}} after a few runs:
{{out}} after a few runs:
Line 1,014: Line 2,165:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>SYSTEM(RUN) ! start this script in RUN-mode
<syntaxhighlight lang="hicest">SYSTEM(RUN) ! start this script in RUN-mode


CHARACTER notes="Notes.txt", txt*1000
CHARACTER notes="Notes.txt", txt*1000
Line 1,033: Line 2,184:
ENDIF
ENDIF


ALARM(999) ! quit HicEst immediately</lang>
ALARM(999) ! quit HicEst immediately</syntaxhighlight>
<pre>Thu 2010-09-16 18:42:15
<pre>Thu 2010-09-16 18:42:15
This is line 1
This is line 1
Line 1,042: Line 2,193:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==


<syntaxhighlight lang="icon">
<lang Icon>
procedure write_out_notes (filename)
procedure write_out_notes (filename)
file := open (filename, "rt") | stop ("no notes file yet")
file := open (filename, "rt") | stop ("no notes file yet")
Line 1,063: Line 2,214:
else add_to_notes (notes_file, args)
else add_to_notes (notes_file, args)
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,083: Line 2,234:
=={{header|J}}==
=={{header|J}}==
'''Solution''':<br>
'''Solution''':<br>
<syntaxhighlight lang="j">#!/usr/bin/ijconsole
<lang j>require 'files strings'
require 'files strings'


notes=: monad define
notes=: monad define
Line 1,095: Line 2,247:


notes 2}.ARGV
notes 2}.ARGV
exit 0</lang>
exit 0</syntaxhighlight>


Under OSX, replace <tt>/usr/bin/ijconsole</tt> with a version specific path such at /Applications/j602/bin/jconsole
Create a Shortcut called <tt>Notes</tt> that calls the script above using the Target:<br>

Under Windows (where the #! line is irrelevant), create a Shortcut called <tt>Notes</tt> that calls the script above using the Target:<br>
<tt>"c:\program files\j602\bin\jconsole.exe" path\to\script\notes.ijs</tt><br>
<tt>"c:\program files\j602\bin\jconsole.exe" path\to\script\notes.ijs</tt><br>
and Start in: <tt>.\</tt>
and Start in: <tt>.\</tt>
Line 1,118: Line 2,272:


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.io.*;
<syntaxhighlight lang="java">import java.io.*;
import java.nio.channels.*;
import java.nio.channels.*;
import java.util.Date;
import java.util.Date;
Line 1,138: Line 2,292:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var notes = 'NOTES.TXT';
<syntaxhighlight lang="javascript">var notes = 'NOTES.TXT';


var args = WScript.Arguments;
var args = WScript.Arguments;
Line 1,167: Line 2,321:
f.WriteLine();
f.WriteLine();
f.Close();
f.Close();
}</lang>
}</syntaxhighlight>
<pre>> del NOTES.TXT
<pre>> del NOTES.TXT
> cscript /nologo notes.js
> cscript /nologo notes.js
Line 1,176: Line 2,330:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>using Dates
<syntaxhighlight lang="julia">using Dates


const filename = "NOTES.TXT"
const filename = "NOTES.TXT"
Line 1,188: Line 2,342:
end
end
close(fp)
close(fp)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.2.10
<syntaxhighlight lang="scala">// version 1.2.10


import java.io.File
import java.io.File
Line 1,210: Line 2,364:
f.appendText(notes)
f.appendText(notes)
}
}
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 1,222: Line 2,376:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


local(
local(
Line 1,243: Line 2,397:
else
else
#notesfile -> exists ? stdout(#notesfile -> readstring)
#notesfile -> exists ? stdout(#notesfile -> readstring)
}</lang>
}</syntaxhighlight>


Called with:
Called with:
<lang Lasso>./notes "Rosetta was here" Räksmörgås
<syntaxhighlight lang="lasso">./notes "Rosetta was here" Räksmörgås
./notes First Second Last
./notes First Second Last
./notes
./notes
</syntaxhighlight>
</lang>
<pre>2013-11-15 11:43:08
<pre>2013-11-15 11:43:08
Rosetta was here, Räksmörgås
Rosetta was here, Räksmörgås
Line 1,257: Line 2,411:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>filename = "NOTES.TXT"
<syntaxhighlight lang="lua">filename = "NOTES.TXT"


if #arg == 0 then
if #arg == 0 then
Line 1,277: Line 2,431:


fp:close()
fp:close()
end</lang>
end</syntaxhighlight>


=={{header|Mathematica}}==
=={{header|M2000 Interpreter}}==
M2000 Interpreter run M2000 environment, which is a Windows program (written in VB6). So for using console we have to use Kernel32 AttachConsole. When we start M2000.exe with a gsb file, the console of M2000 not opened until we execute a Show command or we use an input statement. So we can run this code without opening M2000 console. There is a tiny lag (observable) when start the environment (can open many times at the same time), there is a stack capacity check, and the M2000.exe make about 30MByte stack (from 1Mbyte the default for VB6).
<lang>If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"];


How to run this example:

Write the code on a UTF-8 text file as notes.gsb

Assign gsb files to open with M2000.exe (the M2000 environment)

Open the folder where exist notes.gsb in a cmd window and execute it writing notes.gsb to get the notes.bat. Now you can write notes your note here.


<syntaxhighlight lang="m2000 interpreter">
MODULE GLOBAL interpret {
global filename$="notes.txt"
declare FreeConsole lib "Kernel32.FreeConsole"
declare GetStdHandle lib "Kernel32.GetStdHandle" {long a}
declare AttachConsole lib "Kernel32.AttachConsole" {long a}
declare CloseHandle lib "Kernel32.CloseHandle" {long a}
declare global WriteCons Lib "Kernel32.WriteConsoleW" {long cons, a$, long n, Long p, long u}
long STD_OUTPUT_HANDLE=-11
global retvalue
buffer clear retvalue as long
ret=AttachConsole(-1)
if ret=0 then beep: exit
global m=GetStdHandle(STD_OUTPUT_HANDLE)
if not islet then
try {
open "notes.bat" for output as #f
print #f, {@}+appdir$+{m2000.exe data {%*}: dir %cd%:load notes
}
close #f
}
PrintConsoleLn("")
dos "notes.bat"
else
read cmd$
cmd$=trim$(cmd$)
if cmd$="" then
if exist(filename$) then
open filename$ for wide input exclusive as #f
while not eof(#f)
line input #f, line$
PrintConsoleLn(line$)
end while
close#
end if
else
if exist(filename$) then
try ok {
open filename$ for wide append exclusive as #f
}
else
try ok {
open filename$ for wide output exclusive as #f
}
end if
if ok then
print #f, str$(now+today,"YYYY-MM-DD hh:mm:ss")
print #f, chr$(9);@RemoveSpaces$(cmd$)
close#f
end if
end if
end if
call void closehandle(m)
call void freeconsole()
Sub PrintConsole(a$)
Call Void WriteCons(m, a$, Len(a$), retvalue(0), 0)
End Sub
Sub PrintConsoleLn(a$)
a$+={
}
Call Void WriteCons(m, a$, Len(a$), retvalue(0), 0)
End Sub
Function RemoveSpaces$(a$)
local b$,c$,i, sk
for i=1 to len(a$)
b$=mid$(a$,i,1)
if sk then
c$+=b$
if b$=""""then
sk=false
b$=mid$(a$,i+1,1)
if b$<>"" and b$<>" " then c$+=" "
end if
else.if mid$(a$,i,2)<>" "then
c$+=b$:if b$=""""then sk=true
end if
next
=c$
End Function
}
module interpret1 {
try {interpret}
}
interpret1: end
</syntaxhighlight>
{{out}}
<pre>
>notes this is "a b" a note.
>notes this is another note.
>notes
2022-11-29 19:32:26
this is "a b" a note
2022-11-29 19:32:45
this is another note.
</pre>



=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"];
Print[ReadString[str, EndOfFile]]; Close[str],
Print[ReadString[str, EndOfFile]]; Close[str],
str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]];
str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]];
WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]];
WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]];
Close[str]]</lang>
Close[str]]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<lang Matlab> function notes(varargin)
<syntaxhighlight lang="matlab"> function notes(varargin)
% NOTES can be used for taking notes
% NOTES can be used for taking notes
% usage:
% usage:
Line 1,313: Line 2,579:
fprintf(fid,'\n');
fprintf(fid,'\n');
fclose(fid);
fclose(fid);
end; </lang>
end; </syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang mercury>:- module notes.
<syntaxhighlight lang="mercury">:- module notes.
:- interface.
:- interface.


Line 1,376: Line 2,642:
notes_filename = "NOTES.TXT".
notes_filename = "NOTES.TXT".


:- end_module notes.</lang>
:- end_module notes.</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import os, times, strutils
<syntaxhighlight lang="nim">import os, times, strutils


if paramCount() == 0:
if paramCount() == 0:
Line 1,386: Line 2,652:
else:
else:
var f = open("notes.txt", fmAppend)
var f = open("notes.txt", fmAppend)
f.writeln getTime()
f.writeLine getTime()
f.writeln "\t", commandLineParams().join(" ")
f.writeLine "\t", commandLineParams().join(" ")
f.close()</lang>
f.close()</syntaxhighlight>
Sample format.txt:
Sample format.txt:
<pre>Mon Jul 14 03:37:20 2014
<pre>2021-04-21T15:49:00+02:00
Hello World
Hello World
2021-04-21T15:51:17+02:00
Mon Jul 14 03:37:45 2014
Hello World again</pre>
Hello World again</pre>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#! /usr/bin/env ocaml
<syntaxhighlight lang="ocaml">#! /usr/bin/env ocaml
#load "unix.cma"
#load "unix.cma"


Line 1,426: Line 2,692:
if Array.length Sys.argv = 1
if Array.length Sys.argv = 1
then dump_notes()
then dump_notes()
else take_notes()</lang>
else take_notes()</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>functor
<syntaxhighlight lang="oz">functor
import
import
Application
Application
Line 1,462: Line 2,728:
end
end
{Application.exit 0}
{Application.exit 0}
end</lang>
end</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Free Pascal in Delphi mode or Delphi in console mode.
Free Pascal in Delphi mode or Delphi in console mode.


<syntaxhighlight lang="pascal">
<lang Pascal>
{$mode delphi}
{$mode delphi}
PROGRAM notes;
PROGRAM notes;
Line 1,506: Line 2,772:
END;
END;
END.
END.
</syntaxhighlight>
</lang>


{{out|Program usage and output}}
{{out|Program usage and output}}
Line 1,521: Line 2,787:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>my $file = 'notes.txt';
<syntaxhighlight lang="perl">my $file = 'notes.txt';
if ( @ARGV ) {
if ( @ARGV ) {
open NOTES, '>>', $file or die "Can't append to file $file: $!";
open NOTES, '>>', $file or die "Can't append to file $file: $!";
Line 1,529: Line 2,795:
print <NOTES>;
print <NOTES>;
}
}
close NOTES;</lang>
close NOTES;</syntaxhighlight>


{{out}} after a few runs:
{{out}} after a few runs:
Line 1,540: Line 2,806:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
Copy of [[Take_notes_on_the_command_line#Euphoria|Euphoria]]
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<lang Phix>constant cmd = command_line()
<span style="color: #008080;">constant</span> <span style="color: #000000;">cmd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">(),</span>
constant filename = "notes.txt"
<span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"notes.txt"</span>
integer fn
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span>
object line
<span style="color: #004080;">object</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
if length(cmd)<3 then
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)?</span><span style="color: #000000;">text</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"&lt;empty&gt;"</span><span style="color: #0000FF;">))</span>
fn = open(filename,"r")
<span style="color: #008080;">else</span>
if fn!=-1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">)</span>
while 1 do
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d-%02d-%02d %d:%02d:%02d\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">date</span><span style="color: #0000FF;">())</span>
line = gets(fn)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\t%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..$]))</span>
if atom(line) then exit end if
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
puts(1,line)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<!--</syntaxhighlight>-->
close(fn)
end if
else
fn = open(filename,"a") -- if such file doesn't exist it will be created
printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date())
printf(fn,"\t%s\n",join(cmd[3..$]))
close(fn)
end if</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
#!/usr/bin/php
#!/usr/bin/php
<?php
<?php
Line 1,574: Line 2,833:
else
else
@readfile('notes.txt');
@readfile('notes.txt');
</syntaxhighlight>
</lang>
Note that the error suppression operator (@) is considered bad coding practice.
Note that the error suppression operator (@) is considered bad coding practice.


Line 1,590: Line 2,849:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
<syntaxhighlight lang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l


(load "@lib/misc.l")
(load "@lib/misc.l")
Line 1,596: Line 2,855:
(out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
(out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
(and (info "notes.txt") (in "notes.txt" (echo))) )
(and (info "notes.txt") (in "notes.txt" (echo))) )
(bye)</lang>
(bye)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>NOTES: procedure (text) options (main); /* 8 April 2014 */
<syntaxhighlight lang="pl/i">NOTES: procedure (text) options (main); /* 8 April 2014 */
declare text character (100) varying;
declare text character (100) varying;
declare note_file file;
declare note_file file;
Line 1,635: Line 2,894:
put file (note_file) skip;
put file (note_file) skip;
put skip list ('The file, NOTES.TXT, has been created');
put skip list ('The file, NOTES.TXT, has been created');
end NOTES;</lang>
end NOTES;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$notes = "notes.txt"
<syntaxhighlight lang="powershell">$notes = "notes.txt"
if (($args).length -eq 0) {
if (($args).length -eq 0) {
if(Test-Path $notes) {
if(Test-Path $notes) {
Line 1,646: Line 2,905:
Get-Date | Add-Content $notes
Get-Date | Add-Content $notes
"`t" + $args -join " " | Add-Content $notes
"`t" + $args -join " " | Add-Content $notes
}</lang>
}</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>#FileName="notes.txt"
<syntaxhighlight lang="purebasic">#FileName="notes.txt"
Define argc=CountProgramParameters()
Define argc=CountProgramParameters()
If OpenConsole()
If OpenConsole()
Line 1,672: Line 2,931:
EndIf
EndIf
EndIf
EndIf
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>import sys, datetime, shutil
<syntaxhighlight lang="python">import sys, datetime, shutil


if len(sys.argv) == 1:
if len(sys.argv) == 1:
try:
try:
with open('notes.txt', 'r') as f:
with open("notes.txt", "r") as f:
shutil.copyfileobj(f, sys.stdout)
shutil.copyfileobj(f, sys.stdout)
except IOError:
except IOError:
pass
pass
else:
else:
with open('notes.txt', 'a') as f:
with open("notes.txt", "a") as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write(datetime.datetime.now().isoformat() + "\n")
f.write("\t%s\n" % ' '.join(sys.argv[1:]))</lang>
f.write("\t%s\n" % ' '.join(sys.argv[1:]))</syntaxhighlight>


'''Sample notes.txt file'''
'''Sample notes.txt file'''
Line 1,697: Line 2,956:


=={{header|R}}==
=={{header|R}}==
<lang R>#!/usr/bin/env Rscript --default-packages=methods
<syntaxhighlight lang="r">#!/usr/bin/env Rscript --default-packages=methods


args <- commandArgs(trailingOnly=TRUE)
args <- commandArgs(trailingOnly=TRUE)
Line 1,708: Line 2,967:
cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
}
}
close(conn)</lang>
close(conn)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#!/usr/bin/env racket
#!/usr/bin/env racket
#lang racket
#lang racket
Line 1,727: Line 2,986:
(date->string (current-date) #t)
(date->string (current-date) #t)
(string-join notes))))))
(string-join notes))))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>my $file = 'notes.txt';
<syntaxhighlight lang="raku" line>my $file = 'notes.txt';


multi MAIN() {
multi MAIN() {
Line 1,742: Line 3,001:
$fh.say: DateTime.now, "\n\t", @note;
$fh.say: DateTime.now, "\n\t", @note;
$fh.close;
$fh.close;
}</lang>
}</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Notes"
Title: "Notes"
URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line
URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line
Line 1,756: Line 3,015:
] [
] [
write/binary/append notes rejoin [now lf tab args lf]
write/binary/append notes rejoin [now lf tab args lf]
]</lang>
]</syntaxhighlight>


{{out|Sample session}}
{{out|Sample session}}
Line 1,771: Line 3,030:
Test line 3
Test line 3
</pre>
</pre>

=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
, <ArgList>: {
= <PrintNotes>;
e.Args = <WriteNote e.Args>;
};
};

ArgList {
= <ArgList 1>;
s.N, <Arg s.N>: {
= ;
e.Arg = (e.Arg) <ArgList <+ s.N 1>>;
};
};

PrintNotes {
, <ExistFile 'notes.txt'>: {
False = ;
True = <PrintFile 1 'notes.txt'>;
};
};

PrintFile {
s.Chan e.File = <Open 'r' s.Chan e.File> <PrintFile (s.Chan)>;
(s.Chan), <Get s.Chan>: {
0 = <Close s.Chan>;
e.Line = <Prout e.Line> <PrintFile (s.Chan)>;
};
};

WriteNote {
e.Args, <Time> '\n\t' <Join (' ') e.Args> '\n': e.Note =
<Open 'a' 2 'notes.txt'>
<Put 2 e.Note>
<Close 2>;
};

Join {
(e.X) = ;
(e.X) (e.1) = e.1;
(e.X) (e.1) e.2 = e.1 e.X <Join (e.X) e.2>;
};</syntaxhighlight>
{{out}}
<pre>$ ls notes.*
notes.ref notes.rsl
$ refgo notes
$ refgo notes This is a note
$ refgo notes This is another note
$ refgo notes Note that this is a note
$ refgo notes
Mon Apr 8 13:57:34 2024
This is a note

Mon Apr 8 13:57:38 2024
This is another note

Mon Apr 8 13:57:42 2024
Note that this is a note

$ ls notes.*
notes.ref notes.rsl notes.txt
$</pre>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program implements the "NOTES" command (append text to a file from the C.L.).*/
<syntaxhighlight lang="rexx">/*REXX program implements the "NOTES" command (append text to a file from the C.L.). */
notes = 'notes.txt' /*the fileID of the 'notes' file. */
timestamp=right(date(),11,0) time() date('W') /*create a (current) date & time stamp.*/
Select
nFID = 'NOTES.TXT' /*the fileID of the "notes" file. */
When arg(1)='?' Then Do
Say "'rexx notes text' appends text to file" notes
Say "'rexx notes' displays file" notes
End
When arg()==0 Then Do /*No arguments? Then display the file.*/
Do while lines(notes)>0
Say linein(notes) /* display a line of file --> screen. */
End
End
Otherwise Do
timestamp=right(date(),11,0) time() date('W') /*create current date & time stamp */
If 'f2'x==2 Then tab='05'x /* this is an EBCDIC system. */
Else tab='09'x /* " " " ASCII " */
Call lineout notes,timestamp /*append the timestamp to "notes" file.*/
Call lineout notes,tab||arg(1) /* " " text " " " */
End
End /*stick a fork in it, we're all Done. */</syntaxhighlight>
{{out}}
<pre>
K:\>rexx notes ?
'rexx notes text' appends text to file notes.txt
'rexx notes' displays file notes.txt

K:\>rexx notes starting work


07 Aug 2023 19:39:41 Monday
if 'f2'x==2 then tab="05"x /*this is an EBCDIC system. */
starting work</pre>
else tab="09"x /* " " " ASCII " */


=={{header|RPL}}==
if arg()==0 then do while lines(nFID) /*No arguments? Then display the file.*/
The file is idiomatically named <code>Logbook</code> rather than <code>NOTES.TXT</code>.
say linein(Nfid) /*display a line of file ──► screen. */
« '''IFERR''' Logbook '''THEN''' "" '''END'''
end /*while*/
else do
'''IF''' DEPTH 1 > '''THEN''' "\n" + DATE TIME TSTR + '''END'''
'''WHILE''' DEPTH 1 > '''REPEAT''' "\n" + DEPTH ROLL + '''END'''
call lineout nFID,timestamp /*append the timestamp to "notes" file.*/
DUP 'Logbook' STO
call lineout nFID,tab||arg(1) /* " " text " " " */
end
1 DISP 7 FREEZE
» '<span style="color:blue">NOTES</span>' STO
/*stick a fork in it, we're all done. */</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>notes = 'NOTES.TXT'
<syntaxhighlight lang="ruby">notes = 'NOTES.TXT'
if ARGV.empty?
if ARGV.empty?
File.copy_stream(notes, $stdout) rescue nil
File.copy_stream(notes, $stdout) rescue nil
else
else
File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}
File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
This uses version 0.4 of the <code>chrono</code> crate
This uses version 0.4 of the <code>chrono</code> crate
<lang Rust>extern crate chrono;
<syntaxhighlight lang="rust">extern crate chrono;


use std::fs::OpenOptions;
use std::fs::OpenOptions;
Line 1,842: Line 3,189:
add_to_notes(&note.join(" ")).expect("failed to write to NOTES.TXT");
add_to_notes(&note.join(" ")).expect("failed to write to NOTES.TXT");
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang scala>import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
<syntaxhighlight lang="scala">import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
import java.time.LocalDateTime
import java.time.LocalDateTime


Line 1,864: Line 3,211:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
(moved from Racket)
(moved from Racket)
{{works with|Racket}}
{{works with|Racket}}
<lang scheme>#lang racket
<syntaxhighlight lang="scheme">#lang racket
(require racket/date)
(require racket/date)
(define *notes* "NOTES.TXT")
(define *notes* "NOTES.TXT")
Line 1,888: Line 3,235:
(fprintf fo "~a~n\t~a~n" dt ln)))
(fprintf fo "~a~n\t~a~n" dt ln)))
#:mode 'text #:exists 'append)
#:mode 'text #:exists 'append)
]))</lang>
]))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
$ include "getf.s7i";
$ include "getf.s7i";
$ include "time.s7i";
$ include "time.s7i";
Line 1,913: Line 3,260:
end if;
end if;
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>

=={{header|SETL}}==
<syntaxhighlight lang="setl">program notes;
if #command_line = 0 then
show_notes;
else
write_note;
end if;

show_notes::
if (notefile := open('notes.txt', 'r')) = om then
stop;
end if;

loop for line in [getline notefile : until eof(notefile)] do
print(line);
end loop;

close(notefile);

write_note::
notefile := open('notes.txt', 'a');
note := (+/[' ' + a : a in command_line])(2..);
puta(notefile, date + '\n\t' + note + '\n');
close(notefile);
end program;</syntaxhighlight>
{{out}}
<pre>$ ls notes.*
notes.setl
$ setl notes.setl
$ setl notes.setl This is a note
$ setl notes.setl This is another note
$ setl notes.setl
Mon Apr 8 14:27:07 2024
This is a note

Mon Apr 8 14:27:11 2024
This is another note

$ ls notes.*
notes.setl notes.txt</pre>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var file = %f'notes.txt'
<syntaxhighlight lang="ruby">var file = %f'notes.txt'


if (ARGV.len > 0) {
if (ARGV.len > 0) {
Line 1,925: Line 3,313:
var fh = file.open_r
var fh = file.open_r
fh && fh.each { .say }
fh && fh.each { .say }
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,939: Line 3,327:
=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|Macro SNOBOL4 in C}}
{{works with|Macro SNOBOL4 in C}}
<lang snobol>#! /usr/local/bin/snobol4 -b
<syntaxhighlight lang="snobol">#! /usr/local/bin/snobol4 -b
a = 2 ;* skip '-b' parameter
a = 2 ;* skip '-b' parameter
notefile = "notes.txt"
notefile = "notes.txt"
Line 1,950: Line 3,338:
notes = date()
notes = date()
notes = char(9) args
notes = char(9) args
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let args = Process.arguments
let args = Process.arguments
Line 1,993: Line 3,381:


let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
handler?.writeData(strData!)</lang>
handler?.writeData(strData!)</syntaxhighlight>
{{out}}
{{out}}
Example output
Example output
Line 2,004: Line 3,392:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl># Make it easier to change the name of the notes file
<syntaxhighlight lang="tcl"># Make it easier to change the name of the notes file
set notefile notes.txt
set notefile notes.txt


Line 2,020: Line 3,408:
close $f
close $f
}
}
}</lang>
}</syntaxhighlight>
{{out}} after a few runs:
{{out}} after a few runs:
<pre>
<pre>
Line 2,027: Line 3,415:
Thu Apr 01 19:28:49 BST 2010
Thu Apr 01 19:28:49 BST 2010
TODO: Submit notes.tcl to Rosetta Code
TODO: Submit notes.tcl to Rosetta Code
</pre>

=={{header|uBasic/4tH}}==
{{works with|R4}}
The lack of built-in high level time and date functions makes it more difficult than necessary, since they have to be implemented by user defined functions.
<syntaxhighlight lang="text">If Cmd (0) > 1 Then ' if there are commandline arguments
If Set (a, Open ("notes.txt", "a")) < 0 Then
Print "Cannot write \qnotes.txt\q" ' open the file in "append" mode
End ' on error, issue message and exit
EndIf
' write the date and time
Write a, Show (FUNC(_DateStr (Time ())));" ";Show (FUNC(_TimeStr (Time ())))
Write a, "\t"; ' prepend with a tab
For i = 2 To Cmd (0) - 1 ' now write all commandline arguments
Write a, Show (Cmd (i)); " "; ' with the exception of the last one
Next
Write a, Show (Cmd (Cmd (0))) ' write the last argument
Else ' if no commandline arguments are given
If Set (a, Open ("notes.txt", "r")) < 0 Then
Print "Cannot read \qnotes.txt\q" ' open the file in "read" mode
End ' on error, issue message and exit
EndIf
Do While Read (a) ' read until EOF
Print Show (Tok (0)) ' show the entire line
Loop ' and repeat..
EndIf

Close a ' finally, close the file
End

_DateStr ' convert epoch to date string
Param (1)
Local (6)

a@ = a@ / 86400 ' just get the number of days since epoch
b@ = 1970+(a@/365) ' ball parking year, will not be accurate!

d@ = 0
For c@ = 1972 To b@ - 1 Step 4
If (((c@%4) = 0) * ((c@%100) # 0)) + ((c@%400) = 0) Then d@ = d@+1
Next

b@ = 1970+((a@ - d@)/365) ' calculating accurate current year by (x - extra leap days)
e@ = ((a@ - d@)%365)+1 ' if current year is leap, set indicator to 1
f@ = (((b@%4) = 0) * ((b@%100) # 0)) + ((b@%400) = 0)

g@ = 0 ' calculating current month
For c@ = 0 To 11 Until e@ < (g@+1)
g@ = g@ + FUNC(_Monthdays (c@, f@))
Next
' calculating current date
g@ = g@ - FUNC(_Monthdays (c@-1, f@))
' Print a@, d@, e@, f@
Return (Join (Str(b@), FUNC(_Format (c@, "-")), FUNC(_Format (e@ - g@, "-"))))

_TimeStr ' convert epoch to time string
Param (1)
Return (Join(Str((a@%86400)/3600), FUNC(_Format ((a@%3600)/60, ":")), FUNC(_Format (a@%60, ":"))))

_Format Param (2) : Return (Join (Iif (a@<10, Join(b@, "0"), b@), Str (a@)))
_Monthdays Param (2) : Return (((a@ + (a@<7)) % 2) + 30 - ((2 - b@) * (a@=1)))
</syntaxhighlight>
{{out}}
<pre>2022-04-02 14:58:57
This is my first entry.
2022-04-02 14:59:10
It might be useful one day.
2022-04-02 14:59:27
Anyways, it seems this task is DONE!
</pre>
</pre>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Bash version
Bash version
<lang bash>#
<syntaxhighlight lang="bash">#
NOTES=$HOME/notes.txt
NOTES=$HOME/notes.txt
if [[ $# -eq 0 ]] ; then
if [[ $# -eq 0 ]] ; then
Line 2,038: Line 3,498:
date >> $NOTES
date >> $NOTES
echo " $*" >> $NOTES
echo " $*" >> $NOTES
fi</lang>
fi</syntaxhighlight>


"Spoiled Bash kid" version
"Spoiled Bash kid" version
<lang bash>N=~/notes.txt;[[ $# -gt 0 ]] && { date ; echo " $*"; exit 0; } >> $N || [[ -r $N ]] && cat $N</lang>
<syntaxhighlight lang="bash">N=~/notes.txt;[[ $# -gt 0 ]] && { date ; echo " $*"; exit 0; } >> $N || [[ -r $N ]] && cat $N</syntaxhighlight>




Portable version
Portable version
<lang bash>NOTES=$HOME/notes.txt
<syntaxhighlight lang="bash">NOTES=$HOME/notes.txt
if test "x$*" = "x"
if test "x$*" = "x"
then
then
Line 2,055: Line 3,515:
date >> $NOTES
date >> $NOTES
echo " $*" >> $NOTES
echo " $*" >> $NOTES
fi</lang>
fi</syntaxhighlight>


{{omit from|Retro}}
{{omit from|Retro}}


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Imports System.IO
<syntaxhighlight lang="vbnet">Imports System.IO


Module Notes
Module Notes
Line 2,078: Line 3,538:
End Try
End Try
End Function
End Function
End Module</lang>
End Module</syntaxhighlight>

=={{header|Wren}}==
{{libheader|Wren-ioutil}}
{{libheader|Wren-date}}
An awkward task for Wren-cli which currently has no way of determining the current date and time.
We therefore have to ask the user to input it plus the note(s).
<syntaxhighlight lang="wren">import "os" for Process
import "./ioutil" for File, FileUtil
import "./date" for Date

var dateFormatIn = "yyyy|-|mm|-|dd|+|hh|:|MM"
var dateFormatOut = "yyyy|-|mm|-|dd| |hh|:|MM"
var args = Process.arguments
if (args.count == 0) {
if (File.exists("NOTES.TXT")) System.print(File.read("NOTES.TXT"))
} else if (args.count == 1) {
System.print("Enter the current date/time (MM/DD+HH:mm) plus at least one other argument.")
} else {
var dateTime = Date.parse(args[0], dateFormatIn)
var note = "\t" + args[1..-1].join(" ") + "\n"
FileUtil.append("NOTES.TXT", dateTime.format(dateFormatOut) + "\n" + note)
}</syntaxhighlight>

{{out}}
Sample session:
<pre>
$ wren NOTES.wren 2021:09:29+16:50 my first note
$ wren NOTES.wren 2021:09:29+16:51 my second note
$ wren NOTES.wren
2021-09-29 16:50
my first note
2021-09-29 16:51
my second note
</pre>

=={{header|XPL0}}==
Checks for unlikely array overflows have been omitted for simplicity.
<syntaxhighlight lang="xpl0">include xpllib; \Date and Time routines
int I, NotesSize, Ch, CmdArgSize;
char Notes(1_000_000), CmdArg(1000);
[\Read in notes.txt, if it exists
Trap(false); \disable abort on errors
FSet(FOpen("notes.txt", 0), ^i);
OpenI(3);
if GetErr = 0 then \file exists
[I:= 0;
while GetErr = 0 do \GetErr detects end-of-file
[Notes(I):= ChIn(3);
I:= I+1;
];
NotesSize:= I-2; \remove 2 EOFs
];
\Get command-line argument, if any, from command line
I:= 0;
loop [Ch:= ChIn(8);
if Ch = CR then quit;
CmdArg(I):= Ch;
I:= I+1;
];
CmdArg(I):= 0; \terminate string
if I = 0 then \no args, just display notes.txt
for I:= 0 to NotesSize-1 do ChOut(0, Notes(I))
else \open notes.txt for output and append CmdArg
[FSet(FOpen("notes.txt", 1), ^o);
OpenO(3);
for I:= 0 to NotesSize-1 do ChOut(3, Notes(I));
DateOut(3, GetDosDate); ChOut(3, ^ );
TimeOut(3, GetDosTime); CrLf(3);
ChOut(3, Tab); Text(3, CmdArg); CrLf(3);
Close(3);
];
]</syntaxhighlight>

{{out}}
<pre>
18-Apr-2022 1:27:14p
first line
18-Apr-2022 1:27:30p
another line
18-Apr-2022 1:42:02p
final test
</pre>


=={{header|zkl}}==
=={{header|zkl}}==
File notes.zkl:
File notes.zkl:
<lang zkl>const notesName="NOTES.TXT";
<syntaxhighlight lang="zkl">const notesName="NOTES.TXT";
args:=vm.arglist;
args:=vm.arglist;
if (not args)
if (not args)
Line 2,090: Line 3,632:
f.writeln(Time.Date.ctime(),"\n\t",args.concat(" "));
f.writeln(Time.Date.ctime(),"\n\t",args.concat(" "));
f.close();
f.close();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 12:29, 8 April 2024

Task
Take notes on the command line
You are encouraged to solve this task according to the task description, using any language you may know.
Take notes on the command line is part of Short Circuit's Console Program Basics selection.

Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.

11l

:start:
I :argv.len == 1
   print(File(‘notes.txt’).read(), end' ‘’)
E
   V f = File(‘notes.txt’, APPEND)
   f.write(Time().format("YYYY-MM-DD hh:mm:ss\n"))
   f.write("\t"(:argv[1..].join(‘ ’))"\n")

8086 Assembly

This code assembles into a .COM file that runs under MS-DOS.

		bits	16
		cpu	8086
		;;;	MS-DOS PSP locations
cmdlen:		equ	80h		; Amount of characters on cmdline
cmdtail:	equ	82h		; Command line tail
		;;;	MS-DOS system calls
puts:		equ	9h		; Print string to console
date:		equ	2Ah		; Get system date
time:		equ	2Ch		; Get system time
creat:		equ	3Ch		; Create file
open:		equ	3Dh		; Open file 
close:		equ	3Eh		; Close file
read: 		equ	3Fh		; Read from file
write:		equ	40h		; Write to file
lseek:		equ	42h		; Set current file position
exit:		equ	4ch		; Exit
		;;;	File modes
O_RDONLY:	equ	0
O_WRONLY:	equ	1
		;;;	Error codes (well, we only need the one)
ENOTFOUND:	equ	2
		;;;	File positions (again we need only the one)
FP_END:		equ	2 
		;;;	File buffer size
BUFSZ:		equ	4096
section		.text
		org	100h
		cmp	byte [cmdlen],0	; Is the command line empty?
		je	printnotes	; Then, go print current notes
		;;;	Retrieve and format current date and time
		mov	ah,date		; Retrieve date
		int	21h
		mov	di,datefmt	; Fill in date string
		xor	ah,ah
		mov	al,dh		; Write month
		mov	bl,2		; Two digits
		call	asciinum
		add	di,3		; Onwards three positions
		mov	al,dl		; Write day
		mov	bl,2		; Two digits
		call	asciinum
		add	di,3		; Onwards three positions
		mov	ax,cx		; Write year
		mov	bl,4		; Four digits
		call	asciinum
		mov	ah,time		; Get system time
		int	21h
		mov	di,timefmt+6	; Fill in time string
		xor	ah,ah
		mov	al,dh		; Write seconds
		mov	bl,2		; Two digits
		call	asciinum
		sub	di,3		; Back three positions
		mov	al,cl		; Write minutes
		mov	bl,2		; Two digits
		call	asciinum
		cmp	ch,12		; AM or PM?
		jbe 	houram		; <=12, AM
		sub	ch,12 		; PM - subtract 12 hours,
		mov	byte [ampm],'P'	; And set the AM/PM to 'P'(M)
		jmp	wrhours
houram:		and	ch,ch		; Hour 0 is 12:XX:XX AM.
		jnz	wrhours
		mov	ch,12 
wrhours:	sub	di,3		; Back three positions
		mov 	al,ch		; Write hours
		mov	bl,2		; Two digits
		call	asciinum
		;;;	Open or create the NOTES.TXT file
		mov	dx,filnam
		mov	ax,open<<8|O_WRONLY
		int	21h		; Try to open the file
		jnc	writenote	; If successful, go write the note
		cmp 	al,ENOTFOUND	; File not found?
		jne	diefile		; Some other error = print error msg
		mov	ah,creat	; No notes file, try to create it
		xor	cx,cx		; Normal file (no attributes set)
		int	21h
		jc	diefile		; If that fails too, print error msg
		;;;	Write the note to the file
writenote:	mov	bx,ax		; File handle in BX
		mov	ax,lseek<<8|FP_END	; Seek to end of file
		xor	cx,cx		; Offset 0
		xor	dx,dx
		int	21h
		jc	diefile		; Error if it fails
		mov	dx,datetime	; Write the date/time string first
		mov	cx,dtsize
		mov	ah,write
		int	21h
		jc	diefile		; Error if it fails
		mov	cx,bx		; Store file handle in CX
		;;;	Terminate note with \r\n
		xor	bx,bx		; BX = length of command line
		mov	bl,[cmdlen]	; Find 2 bytes past cmd input
		add	bx,cmdlen+1	; Note: this might overwrite the first
		mov	word [bx],0A0Dh	; instruction, but we don't need it
		sub	bx,cmdtail-2	; Get length (add 2 for the 0D0A)
		xchg	bx,cx		; File handle in BX, length in CX
		mov	dx,cmdtail	; Write what's on the command line
		mov	ah,write
		int	21h
		jc	diefile		; Error if it fails.
		jmp	closeexit	; Close file and exit if it succeeds.	
		;;;	Print the contents of the NOTES.TXT file
printnotes:	mov	dx,filnam	; Open file for reading
		mov	ax,open<<8|O_RDONLY
		int	21h
		jnc	readnotes	; Carry flag set = error.
		cmp	al,ENOTFOUND	; File not found?
		jne	diefile		; Some other error = print error msg
		jmp	exitok 		; Not found = no notes = just exit
readnotes:	mov	di,ax 		; Keep the file handle in DI.
.loop		mov	bx,di		; Get file handle for file
		mov	cx,BUFSZ	; Read as many bytes as will fit in the
		mov	ah,read		; buffer
		int	21h
		jc	diefile		; Carry flag set = error
		and	ax,ax		; If 0 bytes read, we're done.
		jz	.done
		xor	bx,bx		; File handle 0 = standard output
		mov	cx,ax		; Write as many bytes as we read
		mov 	ah,write
		int	21h
		jc	diefile
		jmp	.loop		; Go get more bytes if there are any
.done		mov	bx,di		; Done: close the file
closeexit:	mov	ah,close
		int	21h
exitok:		mov	ax,exit<<8|0	; Exit with errorlevel 0 (success)
		int	21h
		;;;	Print 'File error' and exit.
diefile:	mov 	dx,fileerror
		;;;	Print error message in DX and exit
die:		mov	ah,puts		; Print error message
		int	21h
		mov	ax,exit<<8|2	; Exit with errorlevel 2.
		int	21h	
		;;;	Subroutine: write AX as BL-digit ASCII number at [DI]
asciinum:	push	dx		; Store DX and CX
		push	cx
		mov	cx,10 		; CX = divisor
		xor	bh,bh		; We never need >255.
.loop:		xor	dx,dx		; Set high word of division to 0.
		div	cx 		; AX /= CX; DX = AX % CX
		add	dl,'0'		; Make digit ASCII
		dec	bl		; Move forward one digit
		mov	[di+bx],dl	; Store digit
		jnz	.loop		; Are we there yet?
		pop 	cx		; Restore DX and CX
		pop 	dx
		ret
section		.data
datetime:	equ	$		; Start of date/time string.
datefmt:	db	'**/**/**** '	; Date placeholder,
timefmt:	db	'**:**:** '	; Time placeholder,
ampm:		db	'AM'		; AM/PM placeholder.
		db	13,10,9		; \r\n\t
dtsize:		equ	$-datetime	; Size of date/time string.
fileerror:	db	'File error.$'	; Printed on error
filnam:		db	'NOTES.TXT',0	; File name to use
section		.bss
filebuf:	resb	BUFSZ		; 4K file buffer
Output:
A:\>dir/b notes.*
NOTES.COM

A:\>notes

A:\>notes This is a note.

A:\>notes This is another note.

A:\>notes
05/11/2020 07:52:34 PM
	This is a note.
05/11/2020 07:52:38 PM
	This is another note.

A:\>dir/b notes.*
NOTES.COM
NOTES.TXT

A:\>

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
or android 64 bits with application Termux
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program notes64.s   */ 

/************************************/
/* Constantes                       */
/************************************/
.include "../includeConstantesARM64.inc" 
.equ BUFFERSIZE,  10000
.equ O_APPEND,    0x400
.equ GETTIME,     0xa9                       // call system linux gettimeofday

/*******************************************/
/* Structures                               */
/********************************************/
/* example structure  time  */
    .struct  0
timeval_sec:                     //
    .struct  timeval_sec + 8 
timeval_usec:                     //
    .struct  timeval_usec + 8 
timeval_end:
    .struct  0
timezone_min:                     //
    .struct  timezone_min + 8 
timezone_dsttime:                 // 
    .struct  timezone_dsttime + 8 
timezone_end:
/*********************************/
/* Initialized data              */
/*********************************/
.data
szCarriageReturn:   .asciz "\n"
szSpace:            .asciz " "
szLibNoFile:        .asciz "no file notes.txt in this directory\n"
szFileName:         .asciz "notes.txt"
szMessAnoRead:      .asciz "Error read file \n"
szMessAnoTime:      .asciz "Error call time \n"
szMessAnoWrite:     .asciz "Error file write \n"
szMessDate:         .asciz " @/@/@  @:@:@ \n"  // message time
.align 8
tbDayMonthYear:    .quad  0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335
                   .quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
                   .quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
                   .quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:        .skip 24
stTVal:           .skip timeval_end
stTZone:          .skip timezone_end
sBuffer:          .skip BUFFERSIZE
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                 // entry of program 
    mov fp,sp                         // stack address
    ldr x20,[fp]                      // load number of parameters command line
    cmp x20,#1                        // >1  insertion text
    bgt 10f
    mov x0,AT_FDCWD
    ldr x1,qAdrszFileName             // file name
    mov x2,#O_RDONLY                  // flags
    mov x3,#0                         // mode in octal
    mov x8,#OPEN                      // open file, create if not exist
    svc 0 
    cmp x0,#0                         // error open
    ble 99f                           // file no exists ?
    mov x19,x0                        // save FD and if file exist display text
    ldr x1,qAdrsBuffer                // buffer address
    ldr x2,#iBufferSize               // buffersize
    mov x8,READ 
    svc 0 
    cmp x0,#0                         // error read ?
    blt 98f
    ldr x0,qAdrsBuffer                // buffer address
    bl affichageMess                  // and display
    b 50f
10:                                   // multiple parameters in command line
    mov x0,AT_FDCWD
    ldr x1,qAdrszFileName             // file name
    ldr x2,iFlag                      // flags
    mov x3,#0644                      // mode in octal
    mov x8,#OPEN                      // open file, create if not exist
    svc 0 
    cmp x0,#0                         // error open
    ble 96f
    mov x19,x0                         // save FD                    
    ldr x0,qAdrstTVal
    ldr x1,qAdrstTZone
    mov x8,#GETTIME                   // call system function time
    svc 0
    cmp x0,#-1                        // error ?
    beq 97f
    ldr x1,qAdrstTVal
    ldr x0,[x1,timeval_sec]           // timestamp in second
    bl formatTime                     // format date and hour
    mov x1,x0
    mov x2,#0
11:                                   // compute length of time message
    ldrb w3,[x1,x2]
    cmp w3,#0
    beq 12f
    add x2,x2,#1
    b 11b
12: 
    mov x0,x19                         // write time message
    mov x8,#WRITE
    svc 0
    cmp x0,#0                          // error ?
    ble 96f
    mov x5,#2                          // start parameters command line
13:
    mov x0,x19                         // file FD
    ldr x1,[fp,x5,lsl #3]              // load parameter address
    mov x2,#0
14:                                    // compute parameter length 
    ldrb w3,[x1,x2]
    cmp w3,#0
    beq 15f
    add x2,x2,#1
    b 14b
15:                                    // write parameter
    mov x8,#WRITE
    svc 0
    cmp x0,#0                          // error ?
    ble 96f
    mov x0,x19                         // file FD
    ldr x1,iadrszSpace                 // write a space betwin parameters
    mov x2,#1
    mov x8,#WRITE
    svc 0
    add x5,x5,#1                        // increment indixe
    cmp x5,x20                          // parameters maxi ?
    ble 13b                             // no -> loop
    mov x0,x19
    ldr x1,qAdrszCarriageReturn         // write line end
    mov x2,#1
    mov x7,#WRITE
    svc 0

50:                                     // close the file
    mov x0,x19
    mov x8,CLOSE 
    svc 0
    b 100f

96:                                     // error write
    ldr x0,qAdrszMessAnoWrite
    bl affichageMess
    b 100f
97:                                     // error function time
    ldr x0,qAdrszMessAnoTime
    bl affichageMess
    b 100f
98:                                     // error read 
    ldr x0,qAdrszMessAnoRead
    bl affichageMess
    b 100f
    
99:                                     // display message no file in this directory
    ldr x0,qAdrszLibNoFile
    bl affichageMess
100:                                    // standard end of the program 
    mov x0, #0                          // return code
    mov x8,EXIT 
    svc #0                              // perform the system call
 
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsZoneConv:            .quad sZoneConv
qAdrszFileName:           .quad szFileName
qAdrszLibNoFile:          .quad szLibNoFile
qAdrsBuffer:              .quad sBuffer
iBufferSize:              .quad BUFFERSIZE
qAdrszMessAnoRead:        .quad szMessAnoRead
qAdrszMessAnoTime:        .quad szMessAnoTime
qAdrszMessAnoWrite:       .quad szMessAnoWrite
iFlag:                    .quad O_RDWR|O_APPEND|O_CREAT
qAdrstTVal:               .quad stTVal
qAdrstTZone:              .quad stTZone
iadrszSpace:              .quad szSpace
/***************************************************/
/*      formatting time area                       */
/***************************************************/
// x0 contains time area
// x0 return address result string
formatTime:
    stp x2,lr,[sp,-16]!           // save  registers 
    ldr x2,qSecJan2020
    sub x3,x0,x2                  // total secondes to 01/01/2020
    mov x4,60
    udiv x5,x3,x4
    msub x6,x5,x4,x3              // compute secondes
    udiv x3,x5,x4
    msub x7,x3,x4,x5              // compute minutes
    mov x4,24
    udiv x5,x3,x4
    msub x8,x5,x4,x3              // compute hours
    mov x4,(365 * 4 + 1)
    udiv x9,x5,x4
    lsl x9,x9,2                   // multiply by 4 = year1
    udiv x12,x5,x4
    msub x10,x12,x4,x5
    ldr x11,qAdrtbDayMonthYear
    mov x12,3
    mov x13,12
1:
    mul x14,x13,x12
    ldr x15,[x11,x14,lsl 3]       // load days by year
    cmp x10,x15
    bge 2f
    sub x12,x12,1
    cmp x12,0
    cbnz x12,1b
2:                                 // x12 = year2
    mov x16,11
    mul x15,x13,x12
    lsl x15,x15,3                  // * par 8
    add x14,x15,x11
3:
    ldr x15,[x14,x16,lsl 3]        // load days by month
    cmp x10,x15
    bge 4f
    sub x16,x16,1
    cmp x16,0
    cbnz x16,3b
4:                                 // x16 = month - 1
    mul x15,x13,x12
    add x15,x15,x16
    ldr x1,qAdrtbDayMonthYear
    ldr x3,[x1,x15,lsl 3]
    sub x0,x10,x3
    add x0,x0,1                    // final compute day
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrszMessDate
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at first @ character
    mov x2,x0
    add x0,x16,1                   // final compute month
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next @ character
    mov x2,x0
    add x0,x9,2020
    add x0,x0,x12                  // final compute year = 2020 + year1 + year2
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next @ character
    mov x2,x0
    mov x0,x8                      // hours
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next @ character
    mov x2,x0
    mov x0,x7                      // minutes
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next @ character
    mov x2,x0
    mov x0,x6                      // secondes
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x4,#0                      // store zero final
    strb w4,[x1,x0]
    mov x0,x2
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at next // character
100:
    ldp x2,lr,[sp],16              // restaur  registers
    ret 
qAdrszMessDate:           .quad szMessDate
qSecJan2020:              .quad 1577836800
qAdrtbDayMonthYear:       .quad tbDayMonthYear

/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../includeARM64.inc"
Output:
~/.../rosetta/asm3 $ notes64
 11/4/2023  15:16:29
initialisation
 11/4/2023  15:16:45
verification
 11/4/2023  15:17:15
suite modification revoir le cas

Ada

Works with: Ada 2005
with Ada.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.IO_Exceptions;
with Ada.Text_IO;
procedure Notes is
   Notes_Filename : constant String := "notes.txt";
   Notes_File     : Ada.Text_IO.File_Type;
   Argument_Count : Natural         := Ada.Command_Line.Argument_Count;
begin
   if Argument_Count = 0 then
      begin
         Ada.Text_IO.Open
           (File => Notes_File,
            Mode => Ada.Text_IO.In_File,
            Name => Notes_Filename);
         while not Ada.Text_IO.End_Of_File (File => Notes_File) loop
            Ada.Text_IO.Put_Line (Ada.Text_IO.Get_Line (File => Notes_File));
         end loop;
      exception
         when Ada.IO_Exceptions.Name_Error =>
            null;
      end;
   else
      begin
         Ada.Text_IO.Open
           (File => Notes_File,
            Mode => Ada.Text_IO.Append_File,
            Name => Notes_Filename);
      exception
         when Ada.IO_Exceptions.Name_Error =>
            Ada.Text_IO.Create (File => Notes_File, Name => Notes_Filename);
      end;
      Ada.Text_IO.Put_Line
        (File => Notes_File,
         Item => Ada.Calendar.Formatting.Image (Date => Ada.Calendar.Clock));
      Ada.Text_IO.Put (File => Notes_File, Item => Ada.Characters.Latin_1.HT);
      for I in 1 .. Argument_Count loop
         Ada.Text_IO.Put
           (File => Notes_File,
            Item => Ada.Command_Line.Argument (I));
         if I /= Argument_Count then
            Ada.Text_IO.Put (File => Notes_File, Item => ' ');
         end if;
      end loop;
      Ada.Text_IO.Flush (File => Notes_File);
   end if;
   if Ada.Text_IO.Is_Open (File => Notes_File) then
      Ada.Text_IO.Close (File => Notes_File);
   end if;
end Notes;

Aime

#! /usr/local/bin/aime -a

if (argc() == 1) {
    file f;
    text s;

    f.affix("NOTES.TXT");

    while (~f.line(s)) {
        o_(s, "\n");
    }
} else {
    date d;
    file f;

    f.open("NOTES.TXT", OPEN_APPEND | OPEN_CREATE | OPEN_WRITEONLY, 0644);

    d.now;

    f.form("/f4/-/f2/-/f2/ /f2/:/f2/:/f2/\n", d.year, d.y_month,
           d.m_day, d.d_hour, d.h_minute, d.m_second);

    for (integer i, text s in 1.args) {
        f.bytes(i ? ' ' : '\t', s);
    }

    f.byte('\n');
}

Amazing Hopper

/*
Take notes on the command line. Rosettacode.org
*/
#include <basico.h>

algoritmo
   
   cuando ' no existe el archivo ("NOTES.txt") ' {
       sys = `touch NOTES.txt`; luego limpiar 'sys'
   }
       
   si ' total argumentos es (1) '
       cargar cadena desde ("NOTES.txt"); luego imprime
   sino
       msg=""; obtener todos los parámetros, guardar en 'msg'
       #( msg = strtran("@","\n\t",msg) )
       fijar separador 'NULO'
       fecha y hora, "\n\t", msg, "\n\n", unir esto;
       añadir al final de ("NOTES.txt")
   fin si
terminar
Output:
:
:
$ hopper3 basica/notes.bas otra y otra y otra...@y otra
$ hopper3 basica/notes.bas
27/11/2023,23:38:28:74
	iniciando estas notas con un mensaje
	de prueba 

27/11/2023,23:40:57:41
	nota 2:
	establecer parámetro 

27/11/2023,23:52:22:82
	nueva nota de prueba
	ta es medianoche 

27/11/2023,23:55:07:20
	otra nueva nota 

27/11/2023,23:56:21:15
	otra y otra y otra...
	y otra 

$ hopper3 basica/notes.bas borrar todo de este directorio@sin asco
$ hopper3 basica/notes.bas
27/11/2023,23:38:28:74
	iniciando estas notas con un mensaje
	de prueba 

27/11/2023,23:40:57:41
	nota 2:
	establecer parámetro 

27/11/2023,23:52:22:82
	nueva nota de prueba
	ta es medianoche 

27/11/2023,23:55:07:20
	otra nueva nota 

27/11/2023,23:56:21:15
	otra y otra y otra...
	y otra 

28/11/2023,00:04:04:62
	borrar todo de este directorio
	sin asco 

$ 

APL

Works with: GNU APL
#!/usr/local/bin/apl -s --

rch Join ls                          ⍝ Join list of strings with character 
        r1↓∊ch,¨ls


dDate                                ⍝ Get system date as formatted string
        d'/'Join ¨13⎕TS


tTime;t24                            ⍝ Get system time as formatted string
        tt2433⎕TS                  ⍝ Get system time
        t[1]t[1]-12×t24[1]12         ⍝ If PM (hour≥12), subtract 12 from hour
        t[1]t[1]+12×t[1]=0            ⍝ Hour 0 is hour 12 (AM)
        t¯2¨'0',¨¨t                 ⍝ Convert numbers to 2-digit strings
        t(':'Join t),(1+t24[1]12)' AM' ' PM'  ⍝ Add AM/PM and ':' separator


Read;f
        (¯2f⎕FIO[49]'notes.txt')/0  ⍝ Read file, stop if not found
        f                           ⍝ Output file line by line


Write note;f;_
        note' 'Join note              ⍝ flatten input and separate with spaces
        noteDate,' ',Time,(⎕UCS 10 9),note,⎕UCS 10   ⍝ note format
        f'a'⎕FIO[3]'notes.txt'        ⍝ append to file
        _(⎕UCS note)⎕FIO[7]f          ⍝ write note to end of file
        _⎕FIO[4]f                     ⍝ close the file


Notes;note
        ⍎∊('Read' 'Write note')[1+0≠⍴note4⎕ARG]


Notes
)OFF
Output:
$ ls notes.*
notes.apl
$ ./notes.apl

$ ./notes.apl This is a test

$ ./notes.apl This is another test

$ ./notes.apl Note that this is a test

$ ./notes.apl
5/11/2020 09:33:14 PM
        This is a test
5/11/2020 09:33:18 PM
        This is another test
5/11/2020 09:33:36 PM
        Note that this is a test

$ ls notes.*
notes.apl  notes.txt

AppleScript

Requires a modernish version of OS X (Lion or later) on which osascript works as a shebang interpreter.

#!/usr/bin/osascript

-- format a number as a string with leading zero if needed
to format(aNumber)
  set resultString to aNumber as text
  if length of resultString < 2
    set resultString to "0" & resultString
  end if
  return resultString
end format

-- join a list with a delimiter
to concatenation of aList given delimiter:aDelimiter
  set tid to AppleScript's text item delimiters
  set AppleScript's text item delimiters to { aDelimiter }
  set resultString to aList as text
  set AppleScript's text item delimiters to tid
  return resultString
end join

-- apply a handler to every item in a list, returning
-- a list of the results
to mapping of aList given function:aHandler
  set resultList to {}
  global h
  set h to aHandler
  repeat with anItem in aList
    set resultList to resultList & h(anItem)
  end repeat
  return resultList
end mapping

-- return an ISO-8601-formatted string representing the current date and time
-- in UTC
to iso8601()
    set { year:y,   month:m,     day:d, ¬
          hours:hr, minutes:min, seconds:sec } to ¬
          (current date) - (time to GMT)
    set ymdList to the mapping of { y, m as integer, d } given function:format
    set ymd to the concatenation of ymdList given delimiter:"-"
    set hmsList to the mapping of { hr, min, sec } given function:format
    set hms to the concatenation of hmsList given delimiter:":"
    set dateTime to the concatenation of {ymd, hms} given delimiter:"T"
    return dateTime & "Z"
end iso8601

to exists(filePath)
  try
    filePath as alias
    return true
  on error
    return false
  end try
end exists

on run argv
  set curDir to (do shell script "pwd")
  set notesFile to POSIX file (curDir & "/NOTES.TXT")

  if (count argv) is 0 then
    if exists(notesFile) then
       set text item delimiters to {linefeed}
       return paragraphs of (read notesFile) as text
    else
       log "No notes here."
       return 
    end if
  else
    try 
      set fd to open for access notesFile with write permission
      write (iso8601() & linefeed & tab) to fd starting at eof
      set AppleScript's text item delimiters to {" "}
      write ((argv as text) & linefeed) to fd starting at eof
      close access fd
      return true
    on error errMsg number errNum
      try
         close access fd
      end try
      return "unable to open  " & notesFile & ": " & errMsg
    end try
  end if
end run

ARM Assembly

Works with: as version Raspberry Pi
or android 32 bits with application Termux
/* ARM assembly Raspberry PI  or android 32 bits */
/*  program notes.s   */ 

/* REMARK 1 : this program use routines in a include file 
   see task Include a file language arm assembly 
   for the routine affichageMess conversion10 
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"
.equ BUFFERSIZE,   10000
.equ READ,     3                          @ system call 
.equ WRITE,    4                          @ Linux syscall
.equ OPEN,     5                          @ system call
.equ CLOSE,    6                          @ system call
.equ O_RDONLY, 0                      
.equ O_RDWR,   0x0002                     @ open for reading and writing
.equ O_APPEND, 0x400
.equ O_CREAT,  0x40
.equ GETTIME,  0x4e                       @ call system linux gettimeofday


/*******************************************/
/* Structures                               */
/********************************************/
/* example structure  time  */
    .struct  0
timeval_sec:                     @
    .struct  timeval_sec + 4 
timeval_usec:                     @
    .struct  timeval_usec + 4 
timeval_end:
    .struct  0
timezone_min:                     @
    .struct  timezone_min + 4 
timezone_dsttime:                 @ 
    .struct  timezone_dsttime + 4 
timezone_end:
/*********************************/
/* Initialized data              */
/*********************************/
.data
szCarriageReturn:   .asciz "\n"
szSpace:            .asciz " "
szLibNoFile:        .asciz "no file notes.txt in this directory\n"
szFileName:         .asciz "notes.txt"
szMessAnoRead:      .asciz "Error read file \n"
szMessAnoTime:      .asciz "Error call time \n"
szMessAnoWrite:     .asciz "Error file write \n"
szMessDate:         .asciz " @/@/@  @:@:@ \n"  @ message time
.align 4
tbDayMonthYear:    .int  0,  31,  60,  91, 121, 152, 182, 213, 244, 274, 305, 335
                   .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
                   .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
                   .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:        .skip 24
stTVal:           .skip timeval_end
stTZone:          .skip timezone_end
sBuffer:          .skip BUFFERSIZE
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                 @ entry of program 
    mov fp,sp                         @ stack address
    ldr r4,[fp]                       @ load number of parameters command line
    cmp r4,#1                         @ >1  insertion text
    bgt 10f
    ldr r0,iAdrszFileName             @ file name
    mov r1,#O_RDONLY                  @ flags
    mov r2,#0                         @ mode in octal
    mov r7,#OPEN                      @ oen file, create if not exist
    svc 0 
    cmp r0,#0                         @ error open
    ble 99f                           @ file no exists ?
    mov r8,r0                         @ save FD                                                      @ if exist display text
    ldr r1,iAdrsBuffer                @ buffer address
    ldr r2,#iBufferSize               @ buffersize
    mov r7, #READ                     @ read file
    svc 0 
    cmp r0,#0                         @ error read ?
    blt 98f
    ldr r0,iAdrsBuffer                @ buffer address
    bl affichageMess                  @ and display
    b 50f
10:                                   @ multiple parameters in command line
    ldr r0,iAdrszFileName             @ file name
    ldr r1,iFlag                      @ flags
    mov r2,#0644                      @ mode in octal
    mov r7,#OPEN                      @ open file, create if not exist
    svc 0 
    cmp r0,#0                         @ error open
    ble 96f
    mov r8,r0                         @ save FD                    
    ldr r0,iAdrstTVal
    ldr r1,iAdrstTZone
    mov r7,#GETTIME                   @ call system function time
    svc 0
    cmp r0,#-1                        @ error ?
    beq 97f
    ldr r0,iAdrstTVal
    bl formatTime                     @ format date and hour
    mov r1,r0
    mov r2,#0
11:                                   @ compute length of time message
    ldrb r3,[r1,r2]
    cmp r3,#0
    beq 12f
    add r2,#1
    b 11b
12: 
    mov r0,r8                         @ write time message
    mov r7,#WRITE
    svc 0
    cmp r0,#0                         @ error ?
    ble 96f
    mov r5,#2                         @ start parameters command line
13:
    mov r0,r8                         @ file FD
    ldr r1,[fp,r5,lsl #2]             @ load parameter address
    mov r2,#0
14:                                   @ compute parameter length 
    ldrb r3,[r1,r2]
    cmp r3,#0
    beq 15f
    add r2,#1
    b 14b
15:                                   @ write parameter
    mov r7,#WRITE
    svc 0
    cmp r0,#0                         @ error ?
    ble 96f
    mov r0,r8                         @ file FD
    ldr r1,iadrszSpace                @ write a space betwin parameters
    mov r2,#1
    mov r7,#WRITE
    svc 0
    add r5,#1                         @ increment indixe
    cmp r5,r4                         @ parameters maxi ?
    ble 13b                           @ no -> loop
    mov r0,r8
    ldr r1,iAdrszCarriageReturn       @ write line end
    mov r2,#1
    mov r7,#WRITE
    svc 0

50:                                   @ close the file
    mov r0,r8
    mov r7, #CLOSE
    svc 0
    b 100f

96:                                   @ error write
    ldr r0,iAdrszMessAnoWrite
    bl affichageMess
    b 100f
97:                                   @ error function time
    ldr r0,iAdrszMessAnoTime
    bl affichageMess
    b 100f
98:                                   @ error read 
    ldr r0,iAdrszMessAnoRead
    bl affichageMess
    b 100f
    
99:                                   @ display message no file in this directory
    ldr r0,iAdrszLibNoFile
    bl affichageMess
100:                                  @ standard end of the program 
    mov r0, #0                        @ return code
    mov r7, #EXIT                     @ request to exit program
    svc #0                            @ perform the system call
 
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsZoneConv:            .int sZoneConv
iAdrszFileName:           .int szFileName
iAdrszLibNoFile:          .int szLibNoFile
iAdrsBuffer:              .int sBuffer
iBufferSize:              .int BUFFERSIZE
iAdrszMessAnoRead:        .int szMessAnoRead
iAdrszMessAnoTime:        .int szMessAnoTime
iAdrszMessAnoWrite:       .int szMessAnoWrite
iFlag:                    .int O_RDWR|O_APPEND|O_CREAT
iAdrstTVal:               .int stTVal
iAdrstTZone:              .int stTZone
iadrszSpace:              .int szSpace
/***************************************************/
/*      formatting time area                       */
/***************************************************/
// r0 contains time area
// r0 return address result string
formatTime:
    push {r2-r12,lr}               @ save  registers 
    ldr r1,[r0,#timeval_sec]       @ timestemp in second
    ldr r2,iSecJan2020
    sub r0,r1,r2                   @ total secondes to 01/01/2020
    mov r1,#60
    bl division
    mov r0,r2
    mov r6,r3                      @ compute secondes
    mov r1,#60
    bl division
    mov r7,r3                      @ compute minutes
    mov r0,r2
    mov r1,#24
    bl division
    mov r8,r3                      @ compute hours
    mov r0,r2
    mov r11,r0
    mov r1,#(365 * 4 + 1)
    bl division
    lsl r9,r2,#2                   @ multiply by 4 = year1
    mov r1,#(365 * 4 + 1)
    mov r0,r11
    bl division
    mov r10,r3
    ldr r1,iAdrtbDayMonthYear
    mov r2,#3
    mov r3,#12
1:
    mul r11,r3,r2
    ldr r12,[r1,r11,lsl #2]         @ load days by year
    cmp r10,r12
    bge 2f
    sub r2,r2,#1
    cmp r2,#0
    bne 1b
2:                                 @ r2 = year2
    mov r5,#11
    mul r4,r3,r2
    lsl r4,#2
    add r4,r1
3:
    ldr r12,[r4,r5,lsl #2]         @ load days by month
    cmp r10,r12
    bge 4f
    subs r5,r5,#1
    bne 3b
4:                                 @ r5 = month - 1
    mul r11,r3,r2
    add r11,r5
    ldr r1,iAdrtbDayMonthYear
    ldr r3,[r1,r11,lsl #2]
    sub r0,r10,r3

    add r0,r0,#1                   @ final compute day
    ldr r1,iAdrsZoneConv
    bl conversion10                @ this function do not zero final
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    ldr r0,iAdrszMessDate
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at first @ character
    mov r3,r0
    add r0,r5,#1                   @ final compute month
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    ldr r11,iYearStart
    add r0,r9,r11
    add r0,r0,r2                   @ final compute year = 2020 + year1 + year2
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r8                      @ hours
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r7                      @ minutes
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character
    mov r3,r0
    mov r0,r6                      @ secondes
    ldr r1,iAdrsZoneConv
    bl conversion10
    mov r4,#0                      @ store zero final
    strb r4,[r1,r0]
    mov r0,r3
    ldr r1,iAdrsZoneConv
    bl strInsertAtCharInc          @ insert result at next @ character

100:
    pop {r2-r12,pc}              @ restaur registers
iAdrszMessDate:           .int szMessDate
iSecJan2020:              .int 1577836800
iAdrtbDayMonthYear:       .int tbDayMonthYear
iYearStart:               .int 2020

/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"
~/.../rosetta/asm3 $ notes
 10/4/2023  19:32:34
creation fichier notes
 10/4/2023  19:32:53
affichage fichier
~/.../rosetta/asm3 $ notes saisie des exemples
~/.../rosetta/asm3 $ notes
 10/4/2023  19:32:34
creation fichier notes
 10/4/2023  19:32:53
affichage fichier
 10/4/2023  19:37:58
saisie des exemples

Arturo

notes: "notes.txt"
if? empty? arg [
    if exists? notes -> print read notes
]
else [
    output: (to :string now) ++ "\n" ++
            "\t" ++ (join.with:" " to [:string] arg) ++ "\n"
    write.append notes output
]
Output:

Example notes.txt:

2021-06-03T07:17:21+02:00
	this is a note
2021-06-03T07:17:26+02:00
	this is another note

AutoHotkey

Notes := "Notes.txt"

If 0 = 0 ; no arguments
{
    If FileExist(Notes) {
        FileRead, Content, %Notes%
        MsgBox, %Content%
    } Else
        MsgBox, %Notes% does not exist
    Goto, EOF
}

; date and time, colon, newline (CRLF), tab
Date := A_DD "/" A_MM "/" A_YYYY
Time := A_Hour ":" A_Min ":" A_Sec "." A_MSec
FileAppend, %Date% %Time%:`r`n%A_Tab%, %Notes%

; command line parameters, trailing newline (CRLF)
Loop, %0%
    FileAppend, % %A_Index% " ", %Notes%
FileAppend, `r`n, %Notes%

EOF:

AWK

# syntax: GAWK -f TAKE_NOTES.AWK [notes ... ]
# examples:
#   GAWK -f TAKE_NOTES.AWK Hello world
#   GAWK -f TAKE_NOTES.AWK A "B C" D
#   GAWK -f TAKE_NOTES.AWK
BEGIN {
    log_name = "NOTES.TXT"
    (ARGC == 1) ? show_log() : update_log()
    exit(0)
}
function show_log(  rec) {
    while (getline rec <log_name > 0) {
      printf("%s\n",rec)
    }
}
function update_log(  i,q) {
    print(strftime("%Y-%m-%d %H:%M:%S")) >>log_name
    printf("\t") >>log_name
    for (i=1; i<=ARGC-1; i++) {
      q = (ARGV[i] ~ / /) ? "\"" : ""
      printf("%s%s%s ",q,ARGV[i],q) >>log_name
    }
    printf("\n") >>log_name
}
Output:

from the three example commands

2013-09-20 00:35:41
        Hello world
2013-09-20 00:35:41
        A "B C" D

BASIC

Works with: QuickBASIC version 7

An implementation of DIR$ is all that's required for this to work with older versions of QB.

IF LEN(COMMAND$) THEN
    OPEN "notes.txt" FOR APPEND AS 1
    PRINT #1, DATE$, TIME$
    PRINT #1, CHR$(9); COMMAND$
    CLOSE
ELSE
    d$ = DIR$("notes.txt")
    IF LEN(d$) THEN
        OPEN d$ FOR INPUT AS 1
        WHILE NOT EOF(1)
            LINE INPUT #1, i$
            PRINT i$
        WEND
        CLOSE
    END IF
END IF

Batch File

Works with: Windows NT version 4
@echo off
if %1@==@ (
    if exist notes.txt more notes.txt
    goto :eof
)
echo %date% %time%:>>notes.txt
echo 	%*>>notes.txt

BBC BASIC

This must be compiled to an EXE and run from the command prompt.

      REM!Exefile C:\NOTES.EXE, encrypt, console
      REM!Embed
      LF = 10
      
      SYS "GetStdHandle", -10 TO @hfile%(1)
      SYS "GetStdHandle", -11 TO @hfile%(2)
      SYS "SetConsoleMode", @hfile%(1), 0
      *INPUT 13
      *OUTPUT 14
      ON ERROR PRINT REPORT$ : QUIT ERR
      
      notes% = OPENUP(@dir$ + "NOTES.TXT")
      IF notes% = 0 notes% = OPENOUT(@dir$ + "NOTES.TXT")
      IF notes% = 0 PRINT "Cannot open or create NOTES.TXT" : QUIT 1
      
      IF @cmd$ = "" THEN
        WHILE NOT EOF#notes%
          INPUT #notes%, text$
          IF ASC(text$) = LF text$ = MID$(text$,2)
          PRINT text$
        ENDWHILE
      ELSE
        PTR#notes% = EXT#notes%
        PRINT #notes%,TIME$ : BPUT#notes%,LF
        PRINT #notes%,CHR$(9) + @cmd$ : BPUT#notes%,LF
      ENDIF
      
      CLOSE #notes%
      QUIT

C

#include <stdio.h>
#include <time.h>

#define note_file "NOTES.TXT"

int main(int argc, char**argv)
{
	FILE *note = 0;
	time_t tm;
	int i;
	char *p;

	if (argc < 2) {
		if ((note = fopen(note_file, "r")))
			while ((i = fgetc(note)) != EOF)
				putchar(i);

	} else if ((note = fopen(note_file, "a"))) {
		tm = time(0);
		p = ctime(&tm);

		/* skip the newline */
		while (*p) fputc(*p != '\n'?*p:'\t', note), p++;

		for (i = 1; i < argc; i++)
			fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
	}

	if (note) fclose(note);
	return 0;
}

C#

using System;
using System.IO;
using System.Text;

namespace RosettaCode
{
  internal class Program
  {
    private const string FileName = "NOTES.TXT";

    private static void Main(string[] args)
    {
      if (args.Length==0)
      {
        string txt = File.ReadAllText(FileName);
        Console.WriteLine(txt);
      }
      else
      {
        var sb = new StringBuilder();
        sb.Append(DateTime.Now).Append("\n\t");
        foreach (string s in args)
          sb.Append(s).Append(" ");
        sb.Append("\n");

        if (File.Exists(FileName))
          File.AppendAllText(FileName, sb.ToString());
        else
          File.WriteAllText(FileName, sb.ToString());
      }
    }
  }
}

C++

#include <fstream>
#include <iostream>
#include <ctime>
using namespace std;

#define note_file "NOTES.TXT"

int main(int argc, char **argv)
{
	if(argc>1)
	{
		ofstream Notes(note_file, ios::app);
		time_t timer = time(NULL);
		if(Notes.is_open())
		{
			Notes << asctime(localtime(&timer)) << '\t';
			for(int i=1;i<argc;i++)
				Notes << argv[i] << ' ';
			Notes << endl;
			Notes.close();
		}
	}
	else
	{
		ifstream Notes(note_file, ios::in);
		string line;
		if(Notes.is_open())
		{
			while(!Notes.eof())
			{
				getline(Notes, line);
				cout << line << endl;
			}
			Notes.close();
		}
	}
}

Clojure

(ns rosettacode.notes
  (:use [clojure.string :only [join]]))

(defn notes [notes]
  (if (seq notes)
    (spit
     "NOTES.txt"
     (str (java.util.Date.) "\n" "\t"
          (join " " notes) "\n")
     :append true)
    (println (slurp "NOTES.txt"))))

(notes *command-line-args*)
Output:
rayne@ubuntu:~/cljprojs/rosettacode$ java -cp 'lib/*' clojure.main src/rosettacode/notes.clj I tawt I taw a puddy cat!
rayne@ubuntu:~/cljprojs/rosettacode$ java -cp 'lib/*' clojure.main src/rosettacode/notes.clj I did! I did!
rayne@ubuntu:~/cljprojs/rosettacode$ cat NOTES.txt 
Wed Dec 29 14:09:24 CST 2010
	I tawt I taw a puddy cat!
Wed Dec 29 14:09:28 CST 2010
	I did! I did!
rayne@ubuntu:~/cljprojs/rosettacode$ java -cp 'lib/*' clojure.main src/rosettacode/notes.clj
Wed Dec 29 14:09:24 CST 2010
	I tawt I taw a puddy cat!
Wed Dec 29 14:09:28 CST 2010
	I did! I did!

CLU

% This program uses the "get_argv" function that is supplied iwth
% PCLU in "useful.lib".

NOTEFILE = "notes.txt"

% Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM]
format_date = proc (d: date) returns (string)
    ds: stream := stream$create_output()
    stream$putzero(ds, int$unparse(d.month), 2)
    stream$putc(ds, '/')
    stream$putzero(ds, int$unparse(d.day), 2)
    stream$putc(ds, '/')
    stream$putzero(ds, int$unparse(d.year), 4)
    stream$putc(ds, ' ')
    
    hour: int := d.hour // 12
    if hour=0 then hour:=12 end
    ampm: string := "AM"
    if d.hour>=12 then ampm := "PM" end
    
    stream$putzero(ds, int$unparse(hour), 2)
    stream$putc(ds, ':')
    stream$putzero(ds, int$unparse(d.minute), 2)
    stream$putc(ds, ':')
    stream$putzero(ds, int$unparse(d.second), 2)
    stream$putc(ds, ' ')
    stream$puts(ds, ampm)
    return(stream$get_contents(ds))
end format_date

% Add a note to the file
add_note = proc (note: sequence[string])
    fn: file_name := file_name$parse(NOTEFILE)
    out: stream := stream$open(fn, "append")
    stream$putl(out, format_date(now()))
    
    c: char := '\t'
    for part: string in sequence[string]$elements(note) do 
        stream$putc(out, c)
        stream$puts(out, part)
        c := ' '
    end 
    stream$putc(out, '\n')
    stream$close(out)
end add_note

% Show the notes file, if it exists
show_notes = proc ()
    po: stream := stream$primary_output()
    fn: file_name := file_name$parse(NOTEFILE)
    begin
        inp: stream := stream$open(fn, "read")
        while true do
            stream$putl(po, stream$getl(inp))
            except when end_of_file: break end
        end
        stream$close(inp)
    end except when not_possible(s: string): end
end show_notes

% Add a note if one is given, show the notes otherwise
start_up = proc ()
    note: sequence[string] := get_argv()
    if sequence[string]$empty(note)
        then show_notes()
        else add_note(note)
    end
end start_up
Output:
$ ls
notes
$ ./notes

$ ./notes This is a test
$ ./notes This is another test
$ ./notes Note that this is a test
$ ./notes
12/15/2021 11:18:50 AM
        This is a test
12/15/2021 11:18:52 AM
        This is another test
12/15/2021 11:19:00 AM
        Note that this is a test

$ ls
notes  notes.txt

COBOL

Works with: OpenCOBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. NOTES.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT OPTIONAL notes ASSIGN TO "NOTES.TXT"
               ORGANIZATION LINE SEQUENTIAL
               FILE STATUS note-status.

       DATA DIVISION.
       FILE SECTION.
       FD  notes.
       01  note-record       PIC X(256).

       LOCAL-STORAGE SECTION.
       01  note-status       PIC 99.
           88  notes-ok      VALUE 0 THRU 9.

       01  date-now.
           03  current-year  PIC 9(4).
           03  current-month PIC 99.
           03  current-day   PIC 99.

       01  time-now.
           03  current-hour  PIC 99.
           03  current-min   PIC 99.
           03  current-sec   PIC 99.

       01  args              PIC X(256).

       PROCEDURE DIVISION.
       DECLARATIVES.
       note-error SECTION.
           USE AFTER STANDARD ERROR PROCEDURE ON notes.

           DISPLAY "Error using NOTES.TXT. Error code: " note-status
           .
       END DECLARATIVES.

       main.
           ACCEPT args FROM COMMAND-LINE

*          *> If there are no args, display contents of NOTES.TXT.
           IF args = SPACES
               OPEN INPUT notes

               PERFORM FOREVER
*                  *> READ has no syntax highlighting, but END-READ does.
*                  *> Go figure.
                   READ notes 
                       AT END
                           EXIT PERFORM

                       NOT AT END
                           DISPLAY FUNCTION TRIM(note-record)
                   END-READ
               END-PERFORM
           ELSE
               OPEN EXTEND notes

*              *> Write date and time to file.       
               ACCEPT date-now FROM DATE YYYYMMDD
               ACCEPT time-now FROM TIME
               STRING current-year "-" current-month "-" current-day
                   " " current-hour ":" current-min ":" current-sec
                   INTO note-record
               WRITE note-record
               
*              *> Write arguments to file as they were passed.
               STRING X"09", args INTO note-record
               WRITE note-record
           END-IF

           CLOSE notes

           GOBACK
           .

Common Lisp

(defparameter *notes* "NOTES.TXT")

(defun format-date-time (stream)
  (multiple-value-bind (second minute hour date month year) (get-decoded-time)
    (format stream "~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
            year month date hour minute second)))

(defun notes (args)
  (if args
      (with-open-file (s *notes* :direction :output
                                 :if-exists :append
                                 :if-does-not-exist :create)
        (format-date-time s)
        (format s "~&~A~{~A~^ ~}~%" #\Tab args))
      (with-open-file (s *notes* :if-does-not-exist nil)
        (when s
          (loop for line = (read-line s nil)
                while line
                do (write-line line))))))

(defun main ()
  (notes (uiop:command-line-arguments)))

D

void main(in string[] args) {
    import std.stdio, std.file, std.datetime, std.range;

    immutable filename = "NOTES.TXT";

    if (args.length == 1) {
        if (filename.exists && filename.isFile)
            writefln("%-(%s\n%)", filename.File.byLine);
    } else {
        auto f = File(filename, "a+");
        f.writefln("%s", cast(DateTime)Clock.currTime);
        f.writefln("\t%-(%s %)", args.dropOne);
    }
}
Output:
C:\>notes Permission to speak, sir!
C:\>notes They don't like it up 'em, sir, they don't like it up 'em!
C:\>notes Don't panic! DON'T PANIC!
C:\>notes
2013-Mar-01 17:50:38
        Permission to speak, sir!
2013-Mar-01 17:51:00
        They don't like it up 'em, sir, they don't like it up 'em!
2013-Mar-01 17:52:18
        Don't panic! DON'T PANIC!

Delphi

program notes;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils,
  IOUtils;

const
  FILENAME = 'NOTES.TXT';
  TAB = #9;

var
  sw: TStreamWriter;
  i : integer;

begin
  if ParamCount = 0 then
  begin
    if TFile.Exists(FILENAME) then
      write(TFile.ReadAllText(FILENAME));
  end
  else
  begin
    if TFile.Exists(FILENAME) then
      sw := TFile.AppendText(FILENAME)
    else
      sw := TFile.CreateText(FILENAME);

    sw.Write(FormatDateTime('yyyy-mm-dd hh:nn',Now));
    sw.Write(TAB);
    for i := 1 to ParamCount do
    begin
      sw.Write(ParamStr(i));
      if i < ParamCount then
        sw.Write(' ');
    end;
    sw.WriteLine;
    sw.Free;
  end;
end.

E

#!/usr/bin/env rune

def f := <file:notes.txt>
def date := makeCommand("date")

switch (interp.getArgs()) {
    match [] {
        if (f.exists()) {
            for line in f { print(line) }
        }
    }
    match noteArgs {
        def w := f.textWriter(true)
        w.print(date()[0], "\t", " ".rjoin(noteArgs), "\n")
        w.close()
    }
}

Elixir

Translation of: Erlang
defmodule Take_notes do
  @filename "NOTES.TXT"
  
  def main( [] ), do: display_notes
  def main( arguments ), do: save_notes( arguments )
  
  def display_notes, do: IO.puts File.read!(@filename)

  def save_notes( arguments ) do
    notes = "#{inspect :calendar.local_time}\n\t" <> Enum.join(arguments, " ")
    File.open!(@filename, [:append], fn(file) -> IO.puts(file, notes) end)
  end
end

Take_notes.main(System.argv)

Erlang

#! /usr/bin/env escript

main( Arguments ) ->
	display_notes( Arguments ),
	save_notes( Arguments ).



display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] );
display_notes( _Arguments ) -> ok.

file() -> "NOTES.TXT".

file_contents() -> file_contents( file:read_file(file()) ).

file_contents( {ok, Binary} ) -> Binary;
file_contents( {error, _Error} ) -> <<>>.

save_notes( [] ) -> ok;
save_notes( Arguments ) ->
	Date = io_lib:format( "~p~n", [calendar:local_time()] ),
	Notes = [Date ++ "\t" | [io_lib:format( "~s ", [X]) || X <- Arguments]],
	Existing_contents = file_contents(),
	file:write_file( file(), [Existing_contents, Notes, "\n"] ).

Euphoria

constant cmd = command_line()
constant filename = "notes.txt"
integer fn
object line
sequence date_time

if length(cmd) < 3 then
    fn = open(filename,"r")
    if fn != -1 then
        while 1 do
            line = gets(fn)
            if atom(line) then
                exit
            end if
            puts(1,line)
        end while
        close(fn)
    end if
else
    fn = open(filename,"a") -- if such file doesn't exist it will be created
    date_time = date()
    date_time = date_time[1..6]
    date_time[1] += 1900
    printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date_time)
    line = "\t"
    for n = 3 to length(cmd) do
        line &= cmd[n] & ' '
    end for
    line[$] = '\n'
    puts(fn,line)
    close(fn)
end if

F#

open System;;
open System.IO;;

let file_path = "notes.txt";;

let show_notes () =
    try
        printfn "%s" <| File.ReadAllText(file_path)
    with 
        _ -> printfn "Take some notes first!";;

let take_note (note : string) =
    let now = DateTime.Now.ToString() in 
    let note = sprintf "%s\n\t%s" now note in
    use file_stream = File.AppendText file_path in (* 'use' closes file_stream automatically when control leaves the scope *)
        file_stream.WriteLine note;;

[<EntryPoint>]
let main args =
    match Array.length args with
        | 0 -> show_notes()
        | _ -> take_note <| String.concat " " args;
    0;;

Usage:

> .\TakeNotes.exe
Take some notes first!
> .\TakeNotes.exe some note with multiple words
> .\TakeNotes.exe another note, with coma in it
> .\TakeNotes.exe
2011-10-15 20:36:52
        some note with multiple words
2011-10-15 20:37:22
        another note with coma in it

Factor

#! /usr/bin/env factor
USING: kernel calendar calendar.format io io.encodings.utf8 io.files
sequences command-line namespaces ;

command-line get [
    "notes.txt" utf8 file-contents print
] [
    " " join "\t" prepend
    "notes.txt" utf8 [
        now timestamp>ymdhms print
        print flush
    ] with-file-appender
] if-empty

Fantom

class Notes
{
  public static Void main (Str[] args)
  {
    notesFile := File(`notes.txt`) // the backticks make a URI
    if (args.isEmpty)
    {
      if (notesFile.exists) 
      {
        notesFile.eachLine |line| { echo (line) }
      }
    }
    else
    {
      // notice the following uses a block so the 'printLine/close' 
      // operations are all applied to the same output stream for notesFile
      notesFile.out(true) // 'true' to append to file 
      { 
        printLine ( DateTime.now.toLocale("DD-MM-YY hh:mm:ss").toStr )
        printLine ( "\t" + args.join(" ") )
        close
      }
    }
  }
}

Sample:

$ fan notes.fan started notes file
$ fan notes.fan added second set of notes
$ fan notes.fan and a third
$ fan notes.fan 
30-01-11 12:30:05
	started notes file
30-01-11 12:30:17
	added second set of notes
30-01-11 12:30:30
	and a third

Forth

The following is SwiftForth-specific, and runs in the Forth environment rather than as a standalone terminal application. Win32Forth only needs simple replacements of DATE and TIME . A Unix Forth would come closer to the 'commandline' requirement, as Windows Forths for whatever reason very eagerly discard the Windows console. Because this runs in the Forth environment, the otherwise acceptable application words are stuffed in a wordlist. Standard Forth doesn't have the notion of create-it-if-it-doesn't-exist, so OPEN just tries again with CREATE-FILE if OPEN-FILE fails.

vocabulary note-words
get-current also note-words definitions

\ -- notes.txt 
variable file
: open       s" notes.txt" r/w open-file if
             s" notes.txt" r/w create-file throw then file ! ;
: appending  file @ file-size throw file @ reposition-file throw ;
: write      file @ write-file throw ;
: close      file @ close-file throw ;

\ -- SwiftForth console workaround
9 constant TAB
: type ( c-addr u -- )
  bounds ?do
    i c@ dup TAB = if drop 8 spaces else emit then
  loop ;

\ -- dump notes.txt
create buf 4096 allot
: dump ( -- )
  cr begin buf 4096 file @ read-file throw dup while
    buf swap type
  repeat drop ;

\ -- time and date
: time   @time (time) ;
: date   @date (date) ;

\ -- add note
: cr     s\" \n" write ;
: tab    s\" \t" write ;
: space  s"  " write ;
: add-note ( c-addr u -- ) appending
  date write space time write cr
  tab ( note ) write cr ;

set-current 

\ -- note
: note ( "note" -- )
  open 0 parse dup if add-note
  else 2drop dump then close ;
previous

The following is exactly the same program, but written in 4tH. 4tH has an I/O system which is different from ANS-Forth. The notes file is specified on the commandline.

\ -- notes.txt
include lib/argopen.4th
include lib/ansfacil.4th

\ -- dump notes.txt
4096 buffer: buf
: dump ( -- )
  input 1 arg-open
  begin buf dup 4096 accept dup while type repeat
  drop drop close ;

\ -- time and date
: :00 <# # # [char] : hold #> type ;
: -00 <# # # [char] - hold #> type ;
: .time 0 .r :00 :00 ;
: .date 0 .r -00 -00 ;
 
\ -- add note
: add-note ( c-addr u -- )
  output append [+] 1 arg-open -rot
  time&date .date space .time cr
  9 emit type cr close ;

\ -- note
: note ( "note" -- )
  argn 2 < abort" Usage: notes filename"
  refill drop 0 parse dup if add-note else 2drop dump then ;

note

Fortran

program notes
implicit none
integer                      :: i, length, iargs, lun, ios
integer,dimension(8)         :: values
character(len=:),allocatable :: arg
character(len=256)           :: line
character(len=1),parameter   :: tab=char(9)
   iargs = command_argument_count()
   open(file='notes.txt',newunit=lun,action='readwrite',position='append',status='unknown')
   if(iargs.eq.0)then
      rewind(lun)
      do
         read(lun,'(a)',iostat=ios)line
         if(ios.ne.0)exit
         write(*,'(a)')trim(line)
      enddo
   else
      call date_and_time(VALUES=values)
      write(lun,'(*(g0))')values(1),"-",values(2),"-",values(3),"T",values(5),":",values(6),":",values(7)
      write(lun,'(a)',advance='no')tab
      do i=1,iargs
         call get_command_argument(number=i,length=length)
         arg=repeat(' ',length)
         call get_command_argument(i, arg)
         write(lun,'(a,1x)',advance='no')arg
      enddo
      write(lun,*)
   endif
end program notes
Output:

2022-2-20T18:40:13

       this is an initial note

2022-2-20T18:40:38

       the note of the day 

FreeBASIC

If Len(Command) Then
    Open "notes.txt" For Append As #1
    Print #1, Date, Time
    Print #1, Chr(9); Command
    Close
Else
    If Open("notes.txt" For Input As #1) = 0 Then
        Dim As String lin
        Print "Contenido del archivo:"
        Do While Not Eof(1)
            Line Input #1, lin
            Print lin
        Loop
    Else
        Open "notes.txt" For Output As #1
        Print "Archivo 'NOTES.TXT' creado"
    End If
End If
Close #1
Sleep


Gambas

'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'

Public Sub Main()
Dim sContents As String                                                     'To store the file contents
Dim sArgs As String[] = Args.All                                            'To store all the Command line Arguments

If Not Exist(User.home &/ "NOTES.TXT") Then                                 'If NOTES.TXT doesn't already exist in the current directory then..
  File.Save(User.home &/ "NOTES.TXT", "")                                   'a new NOTES.TXT file should be created.
  Print "New file 'NOTES.TXT' created."                                     'A meassge
Endif

sContents = File.Load(User.home &/ "NOTES.TXT")                             'Get the contents of the file

If Args.count < 2 Then                                                      'If NOTES has arguments (other than the file name)
  Print sContents                                                           'Print the file contents
Else
  sContents &= Format(Now, "dddd dd mmmm, yyyy, hh:nn:ss") & gb.NewLine &   'The current date and time are appended to the local NOTES.TXT followed by a newline and..
     gb.Tab & sArgs.Join(" ") & gb.NewLine                                  'Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline
  Print sContents                                                           'Displays the current contents of the local NOTES.TXT
  File.Save(User.home &/ "NOTES.TXT", sContents)                            'Write contents to NOTES.TXT
Endif

End

Output:

Wednesday 24 May, 2017, 17:55:56
	./CLIOnly.gambas Hello to
Wednesday 24 May, 2017, 17:55:58
	./CLIOnly.gambas Hello to you all

Go

package main

import (
	"fmt"
	"io"
	"os"
	"strings"
	"time"
)

func addNote(fn string, note string) error {
	f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return err
	}
	_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
	// To be extra careful with errors from Close():
	if cErr := f.Close(); err == nil {
		err = cErr
	}
	return err
}

func showNotes(w io.Writer, fn string) error {
	f, err := os.Open(fn)
	if err != nil {
		if os.IsNotExist(err) {
			return nil // don't report "no such file"
		}
		return err
	}
	_, err = io.Copy(w, f)
	f.Close()
	return err
}

func main() {
	const fn = "NOTES.TXT"
	var err error
	if len(os.Args) > 1 {
		err = addNote(fn, strings.Join(os.Args[1:], " "))
	} else {
		err = showNotes(os.Stdout, fn)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Groovy

def notes = new File('./notes.txt')
if (args) {
    notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
} else {
    println notes.text
}

Haskell

import System.Environment (getArgs)
import System.Time (getClockTime)

main :: IO ()
main = do
  args <- getArgs
  if null args
    then catch (readFile "notes.txt" >>= putStr)
               (\_ -> return ())
    else
      do ct <- getClockTime
         appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n"
Output:

after a few runs

Thu Apr 22 19:01:41 PDT 2010
	Test line 1.
Thu Apr 22 19:01:45 PDT 2010
	Test line 2.

HicEst

SYSTEM(RUN) ! start this script in RUN-mode

CHARACTER notes="Notes.txt", txt*1000

! Remove file name from the global variable $CMD_LINE:
EDIT(Text=$CMD_LINE, Mark1, Right=".hic ", Right=4, Mark2, Delete)

IF($CMD_LINE == ' ') THEN
  READ(FIle=notes, LENgth=Lnotes)
  IF( Lnotes ) THEN
    WINDOW(WINdowhandle=hdl, TItle=notes)
    WRITE(Messagebox="?Y") "Finished ?"
  ENDIF
ELSE
  WRITE(Text=txt, Format="UWWW CCYY-MM-DD HH:mm:SS, A") 0, $CRLF//$TAB//TRIM($CMD_LINE)//$CRLF
  OPEN(FIle=notes, APPend)
  WRITE(FIle=notes, CLoSe=1) txt
ENDIF

ALARM(999) ! quit HicEst immediately
Thu 2010-09-16 18:42:15
	This is line 1

Thu 2010-09-16 18:42:23
	This is line 2

Icon and Unicon

procedure write_out_notes (filename)
  file := open (filename, "rt") | stop ("no notes file yet")
  every write (!file)
end

procedure add_to_notes (filename, strs)
  file := open (filename, "at")  | # append to file if it exists
          open (filename, "cat") | # create the file if not there
          stop ("unable to open " || filename)
  writes (file, ctime(&now) || "\n\t")
  every writes (file, !strs || " ")
  write (file, "")
end

procedure main (args)
  notes_file := "notes.txt"
  if *args = 0 
    then write_out_notes (notes_file)
    else add_to_notes (notes_file, args)
end
Output:
$ ./take-notes
no notes file yet
$ ./take-notes finished notes program
$ ./take-notes
Thu Jun  2 23:39:49 2011
	finished notes program 
$ ./take-notes for Unicon
$ ./take-notes
Thu Jun  2 23:39:49 2011
	finished notes program 
Thu Jun  2 23:40:13 2011
	for Unicon 

J

Solution:

#!/usr/bin/ijconsole
require 'files strings'

notes=: monad define
 if. #y do.
   now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY'
   'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y
 elseif. -. _1 -: txt=. fread 'notes.txt' do.
   smoutput txt
 end.
)

notes 2}.ARGV
exit 0

Under OSX, replace /usr/bin/ijconsole with a version specific path such at /Applications/j602/bin/jconsole

Under Windows (where the #! line is irrelevant), create a Shortcut called Notes that calls the script above using the Target:
"c:\program files\j602\bin\jconsole.exe" path\to\script\notes.ijs
and Start in: .\

Example Use:
In a Windows CMD session...

C:\Folder>Notes.lnk "Test line 1"

C:\Folder>Notes.lnk "Test" "line" "2"

C:\Folder>Notes.lnk Test line 3

C:\Folder>Notes.lnk
2010 5 21 11 31 30.389
        Test line 1
2010 5 21 11 31 50.669
        Test line 2
2010 5 21 11 32 14.895
        Test line 3

Java

import java.io.*;
import java.nio.channels.*;
import java.util.Date;

public class TakeNotes {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
            ps.println(new Date());
            ps.print("\t" + args[0]);
            for (int i = 1; i < args.length; i++)
                ps.print(" " + args[i]);
            ps.println();
            ps.close();
        } else {
            FileChannel fc = new FileInputStream("notes.txt").getChannel();
            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
            fc.close();
        }
    }
}

JavaScript

Works with: JScript
var notes = 'NOTES.TXT';

var args = WScript.Arguments;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;

if (args.length == 0) {
    if (fso.FileExists(notes)) {
        var f = fso.OpenTextFile(notes, ForReading);
        WScript.Echo(f.ReadAll());
        f.Close();
    }
}
else {
    var f = fso.OpenTextFile(notes, ForAppending, true);
    var d = new Date();
    f.WriteLine(d.toLocaleString());
    f.Write("\t");
    // note that WScript.Arguments is not an array, it is a "collection"
    // it does not have a join() method.
    for (var i = 0; i < args.length; i++) {
        f.Write(args(i) + " ");
    }
    f.WriteLine();
    f.Close();
}
> del NOTES.TXT
> cscript /nologo notes.js
> cscript /nologo notes.js this   is   the   first note
> cscript /nologo notes.js
April 1, 2010 5:18:38 PM
        this is the first note

Julia

using Dates

const filename = "NOTES.TXT"

if length(ARGS) == 0
    fp = open(filename, "r")
    println(read(fp, String))
else
    fp = open(filename, "a+")
    write(fp, string(DateTime(now()), "\n\t", join(ARGS, " "), "\n"))
end
close(fp)

Kotlin

// version 1.2.10

import java.io.File
import java.util.Date
import java.text.SimpleDateFormat

fun main(args: Array<String>) {
    val f = File("NOTES.TXT")
    // create file if it doesn't exist already
    f.createNewFile()
    if (args.size == 0) {
        println(f.readText())
    }
    else {
        val df = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
        val dt = df.format(Date())
        val notes = "$dt\n\t${args.joinToString(" ")}\n"
        f.appendText(notes)
    }
}

Sample output:

$ java -jar NOTES.jar This is the first note.
$ java -jar NOTES.jar
2018/01/27 18:19:06
	This is the first note.

Lasso

#!/usr/bin/lasso9

local(
	arguments	= $argv -> asarray,
	notesfile	= file('notes.txt')
)

#arguments -> removefirst

if(#arguments -> size) => {

	#notesfile -> openappend
	#notesfile -> dowithclose => {
		#notesfile -> writestring(date -> format(`YYYY-MM-dd HH:mm:SS`) + '\n')
		#notesfile -> writestring('\t' + #arguments -> join(', ') + '\n')
	}



else
	#notesfile -> exists ? stdout(#notesfile -> readstring)
}

Called with:

./notes "Rosetta was here" Räksmörgås
./notes First Second Last
./notes
2013-11-15 11:43:08
	Rosetta was here, Räksmörgås
2013-11-15 11:43:67
	First, Second, Last

Lua

filename = "NOTES.TXT"

if #arg == 0 then
    fp = io.open( filename, "r" )
    if fp ~= nil then
        print( fp:read( "*all*" ) )
        fp:close()
    end
else
    fp = io.open( filename, "a+" )
	
    fp:write( os.date( "%x %X\n" ) )
	
    fp:write( "\t" )
    for i = 1, #arg do
	fp:write( arg[i], " " )
    end
    fp:write( "\n" )

    fp:close()
end

M2000 Interpreter

M2000 Interpreter run M2000 environment, which is a Windows program (written in VB6). So for using console we have to use Kernel32 AttachConsole. When we start M2000.exe with a gsb file, the console of M2000 not opened until we execute a Show command or we use an input statement. So we can run this code without opening M2000 console. There is a tiny lag (observable) when start the environment (can open many times at the same time), there is a stack capacity check, and the M2000.exe make about 30MByte stack (from 1Mbyte the default for VB6).


How to run this example:

Write the code on a UTF-8 text file as notes.gsb

Assign gsb files to open with M2000.exe (the M2000 environment)

Open the folder where exist notes.gsb in a cmd window and execute it writing notes.gsb to get the notes.bat. Now you can write notes your note here.


MODULE GLOBAL interpret {
global filename$="notes.txt"
declare FreeConsole lib "Kernel32.FreeConsole"
declare GetStdHandle lib "Kernel32.GetStdHandle" {long a}
declare AttachConsole lib "Kernel32.AttachConsole" {long a}
declare CloseHandle lib "Kernel32.CloseHandle" {long a}
declare global WriteCons Lib "Kernel32.WriteConsoleW" {long cons, a$,  long n, Long  p, long u}
long STD_OUTPUT_HANDLE=-11
global retvalue
buffer clear retvalue as long
ret=AttachConsole(-1)
if ret=0 then beep: exit
global m=GetStdHandle(STD_OUTPUT_HANDLE)
if not islet then
	try {
		open "notes.bat" for output as #f
		print #f, {@}+appdir$+{m2000.exe data {%*}: dir %cd%:load notes
			}
		close #f
		}
	PrintConsoleLn("")
	dos "notes.bat"
else
	read cmd$
	cmd$=trim$(cmd$)
	if cmd$="" then
		if  exist(filename$) then
			open filename$ for wide input exclusive as #f
			while not eof(#f)
				line input #f, line$
				PrintConsoleLn(line$)
			end while
			close#
		end if
	else
		if  exist(filename$) then
			try ok {
				open filename$ for wide append exclusive as #f
			}
		else
			try ok {
				open filename$ for wide output exclusive as #f
			}
		end if
		if ok then
			print #f, str$(now+today,"YYYY-MM-DD hh:mm:ss")
			print #f, chr$(9);@RemoveSpaces$(cmd$)
			close#f
		end if
	end if
end if
call void closehandle(m)
call void freeconsole()
Sub PrintConsole(a$)
      Call Void WriteCons(m, a$, Len(a$), retvalue(0), 0)
End Sub
Sub PrintConsoleLn(a$)
	a$+={
	}
	Call Void WriteCons(m, a$, Len(a$), retvalue(0), 0)
End Sub
Function RemoveSpaces$(a$)
	local b$,c$,i, sk
	for i=1 to len(a$)
		b$=mid$(a$,i,1)
		if sk then
			c$+=b$
			if b$=""""then
				sk=false
				b$=mid$(a$,i+1,1)
				if b$<>"" and b$<>" " then c$+=" "
			end if
		else.if  mid$(a$,i,2)<>"  "then
			c$+=b$:if b$=""""then sk=true
		end if
	next
	=c$
End Function
}
module interpret1 {
	try  {interpret}
	
}
interpret1: end
Output:
>notes this    is  "a   b"       a  note.
>notes this  is     another note.
>notes
2022-11-29 19:32:26
        this is "a   b" a note
2022-11-29 19:32:45
        this is another note.


Mathematica/Wolfram Language

If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"]; 
 Print[ReadString[str, EndOfFile]]; Close[str], 
 str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]]; 
 WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]]; 
 Close[str]]

MATLAB / Octave

 function notes(varargin)
    % NOTES can be used for taking notes 
    % usage:
    %    notes    displays the content of the file NOTES.TXT
    %    notes arg1 arg2 ... 
    %             add the current date, time and arg# to NOTES.TXT
    %

    filename = 'NOTES.TXT'; 
    if nargin==0
	fid = fopen(filename,'rt');
	if fid<0, return; end; 
	while ~feof(fid)
		fprintf('%s\n',fgetl(fid));
	end; 
	fclose(fid); 
    else
        fid = fopen(filename,'a+');
	if fid<0, error('cannot open %s\n',filename); end; 
        fprintf(fid, '%s\n\t%s', datestr(now),varargin{1});
        for k=2:length(varargin)
            fprintf(fid, ', %s', varargin{k});
	end; 
	fprintf(fid,'\n');
	fclose(fid);
    end;

Mercury

:- module notes.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module list, time.

main(!IO) :-
    io.command_line_arguments(Args, !IO),
    ( if Args = [] then print_notes(!IO) else add_note(Args, !IO) ).

:- pred print_notes(io::di, io::uo) is det.

print_notes(!IO) :-
   io.open_input(notes_filename, InputRes, !IO),
   (
        InputRes = ok(Input),
        io.input_stream_foldl_io(Input, io.write_char, WriteRes, !IO),
        (
            WriteRes = ok
        ;
            WriteRes = error(WriteError),
            print_io_error(WriteError, !IO)
        ),
        io.close_input(Input, !IO)
   ;
        InputRes = error(_InputError)
   ).

:- pred add_note(list(string)::in, io::di, io::uo) is det.

add_note(Words, !IO) :-
   io.open_append(notes_filename, OutputRes, !IO),
   (
       OutputRes = ok(Output),
       time(Time, !IO),
       io.write_string(Output, ctime(Time), !IO),
       io.write_char(Output, '\t', !IO),
       io.write_list(Output, Words, " ", io.write_string, !IO),
       io.nl(Output, !IO),
       io.close_output(Output, !IO)
   ;
       OutputRes = error(OutputError),
       print_io_error(OutputError, !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).

:- func notes_filename = string.

notes_filename = "NOTES.TXT".

:- end_module notes.

Nim

import os, times, strutils

if paramCount() == 0:
  try: stdout.write readFile("notes.txt")
  except IOError: discard
else:
  var f = open("notes.txt", fmAppend)
  f.writeLine getTime()
  f.writeLine "\t", commandLineParams().join(" ")
  f.close()

Sample format.txt:

2021-04-21T15:49:00+02:00
	Hello World
2021-04-21T15:51:17+02:00
	Hello World again

OCaml

#! /usr/bin/env ocaml
#load "unix.cma"

let notes_file = "notes.txt"

let take_notes() =
  let gmt = Unix.gmtime (Unix.time()) in
  let date =
    Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d"
      (1900 + gmt.Unix.tm_year) (1 + gmt.Unix.tm_mon) gmt.Unix.tm_mday
      gmt.Unix.tm_hour gmt.Unix.tm_min gmt.Unix.tm_sec
  in
  let oc = open_out_gen [Open_append; Open_creat; Open_text] 0o644 notes_file in
  output_string oc (date ^ "\t");
  output_string oc (String.concat " " (List.tl(Array.to_list Sys.argv)));
  output_string oc "\n";
;;

let dump_notes() =
  if not(Sys.file_exists notes_file)
  then (prerr_endline "no local notes found"; exit 1);
  let ic = open_in notes_file in
  try while true do
    print_endline (input_line ic)
  done with End_of_file ->
    close_in ic

let () =
  if Array.length Sys.argv = 1
  then dump_notes()
  else take_notes()

Oz

functor
import
   Application
   Open
   OS
   System
define
   fun {TimeStamp}
      N = {OS.localTime}
   in
      (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec
   end

   fun {Join X|Xr Sep}
      {FoldL Xr fun {$ Z X} Z#Sep#X end X}
   end
   
   case {Application.getArgs plain}
   of nil then
      try
         F = {New Open.file init(name:"notes.txt")}
      in
         {System.printInfo {F read(list:$ size:all)}}
         {F close}
      catch _ then skip end      
   [] Args then
      F = {New Open.file init(name:"notes.txt" flags:[write text create append])}
   in
      {F write(vs:{TimeStamp}#"\n")}
      {F write(vs:"\t"#{Join Args " "}#"\n")}
      {F close}
   end
   {Application.exit 0}
end

Pascal

Free Pascal in Delphi mode or Delphi in console mode.

{$mode delphi}
PROGRAM notes;
// Notes: a time-stamped command line notebook
// usage: >notes "note"< or >notes< to display contents  
USES Classes, SysUtils;

VAR
	Note  : TStringList;
	Fname : STRING = 'Notes.txt';
	Dtime : STRING;
	Ntext : STRING;
	c     : Cardinal;
	
BEGIN
	DTime := FormatDateTime('YYYY-MM-DD-hhnn',Now);
	Note  := TStringList.Create;
	WITH Note DO BEGIN
		TRY
			LoadFromFile(Fname);
		EXCEPT
			Add(DTime);
			NText := 'Notes.txt created.';
		END;
		// command line args present:
		// add note with date & time
		IF ParamStr(1) <> '' THEN BEGIN
			NText := ParamStr(1);
			Add(DTime);
			Add(NText);
			SaveToFile(Fname);
		// command line args absent:
		// display contents of notebook
		END ELSE
			FOR c := 0 TO Count-1 DO
				Writeln(Note[c]);
		Free;
	END;
END.
Program usage and output:
>notes "Done: coded notes.pas for RC. It was quick."
>notes
2013-09-18-2243
Notes.txt created.
2013-09-18-2252
To do: code notes.pas for RC.
2013-09-18-2253
Done: coded notes.pas for RC. It was quick.

Perl

my $file = 'notes.txt';
if ( @ARGV ) {
  open NOTES, '>>', $file or die "Can't append to file $file: $!";
  print NOTES scalar localtime, "\n\t@ARGV\n";
} else {
  open NOTES, '<', $file or die "Can't read file $file: $!";
  print <NOTES>;
}
close NOTES;
Output:

after a few runs

Thu Apr 22 19:01:41 2010
	Test line 1.
Thu Apr 22 19:01:45 2010
	Test line 2.

Phix

without js -- (file i/o)
constant cmd = command_line(),
         filename = "notes.txt"
if length(cmd)<3 then
    object text = get_text(filename)
    printf(1,"%s\n",iff(string(text)?text:"<empty>"))
else
    integer fn = open(filename,"a")
    printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date())
    printf(fn,"\t%s\n",join(cmd[3..$]))
    close(fn)
end if

PHP

#!/usr/bin/php
<?php
if ($argc > 1)
    file_put_contents(
        'notes.txt', 
        date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
        FILE_APPEND
    );
else
    @readfile('notes.txt');

Note that the error suppression operator (@) is considered bad coding practice.

Sample notes.txt file

zls@zls:~$ ./notes hello rosetta code
zls@zls:~$ ./notes todo notes program
zls@zls:~$ ./notes 
Tue, 12 Jun 2012 19:27:35 +0200
	hello rosetta code
Tue, 12 Jun 2012 19:27:45 +0200
	todo notes program

PicoLisp

#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(load "@lib/misc.l")
(if (argv)
   (out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
   (and (info "notes.txt") (in "notes.txt" (echo))) )
(bye)

PL/I

NOTES: procedure (text) options (main); /* 8 April 2014 */
   declare text character (100) varying;
   declare note_file file;

   on undefinedfile(note_file) go to file_does_not_exist;
   open file (note_file) title ('/NOTES.TXT,recsize(100),type(text)');
   revert error;

   if text = '' then
      do;
         on endfile (note_file) stop;

         do forever;
            get file (note_file) edit (text) (L);
            put skip list (text);
         end;
      end;
   close file (note_file);
   open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text),append(y)');

   put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
   put file (note_file) skip list (text);
   put file (note_file) skip;

   put skip list ('Appended ' || text || ' to file');

   return;

file_does_not_exist:
   revert undefinedfile (note_file);
   close file (note_file);
   open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text)');
   put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
   put file (note_file) skip list (text);
   put file (note_file) skip;
   put skip list ('The file, NOTES.TXT, has been created');
end NOTES;

PowerShell

$notes = "notes.txt"
if (($args).length -eq 0) {
    if(Test-Path $notes) {
        Get-Content $notes
    }
} else {
    Get-Date | Add-Content $notes
    "`t" + $args -join " " | Add-Content $notes
}

PureBasic

#FileName="notes.txt"
Define argc=CountProgramParameters()
If OpenConsole()
  If argc=0
    If ReadFile(0,#FileName)
      While Eof(0)=0
        PrintN(ReadString(0))                    ; No new notes, so present the old
      Wend
      CloseFile(0)
    EndIf
  Else ; e.g. we have some arguments
    Define d$=FormatDate("%yyyy-%mm-%dd %hh:%ii:%ss",date())
    If OpenFile(0,#FileName)
      Define args$=""
      While argc
        args$+" "+ProgramParameter()             ; Read all arguments
        argc-1
      Wend
      FileSeek(0,Lof(0))                         ; Go to the end of this file
      WriteStringN(0,d$+#CRLF$+#TAB$+args$)      ; Append date & note
      CloseFile(0)
    EndIf
  EndIf
EndIf

Python

import sys, datetime, shutil

if len(sys.argv) == 1:
    try:
        with open("notes.txt", "r") as f:
            shutil.copyfileobj(f, sys.stdout)
    except IOError:
        pass
else:
    with open("notes.txt", "a") as f:
        f.write(datetime.datetime.now().isoformat() + "\n")
        f.write("\t%s\n" % ' '.join(sys.argv[1:]))

Sample notes.txt file

After assorted runs:

2010-04-01T17:06:20.312000
	go for it
2010-04-01T17:08:20.718000
	go for it

R

#!/usr/bin/env Rscript --default-packages=methods

args <- commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  conn <- file("notes.txt", 'r')
  cat(readLines(conn), sep="\n")
} else {
  conn <- file("notes.txt", 'a')
  cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
}
close(conn)

Racket

#!/usr/bin/env racket
#lang racket
(define file "NOTES.TXT")
(require racket/date)
(command-line #:args notes
  (if (null? notes)
    (if (file-exists? file)
      (call-with-input-file* file
        (λ(i) (copy-port i (current-output-port))))
      (raise-user-error 'notes "missing ~a file" file))
    (call-with-output-file* file #:exists 'append
      (λ(o) (fprintf o "~a\n\t~a\n"
                     (date->string (current-date) #t)
                     (string-join notes))))))

Raku

(formerly Perl 6)

my $file = 'notes.txt';

multi MAIN() {
    print slurp($file);
}

multi MAIN(*@note) {
    my $fh = open($file, :a);
    $fh.say: DateTime.now, "\n\t", @note;
    $fh.close;
}

REBOL

REBOL [
   Title: "Notes"
   URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line
]

notes: %notes.txt

either any [none? args: system/script/args  empty? args] [
   if exists? notes [print read notes]
] [
   write/binary/append notes rejoin [now lf tab args lf]
]
Sample session:
> rebol -w notes.r 
> rebol -w notes.r "Test line 1"
> rebol -w notes.r "Test" "line" "2"
> rebol -w notes.r Test line 3
> rebol -w notes.r
4-Oct-2010/21:45:16-5:00
	Test line 1
4-Oct-2010/21:45:27-5:00
	Test line 2
4-Oct-2010/21:45:36-5:00
	Test line 3

Refal

$ENTRY Go {
    , <ArgList>: {
        = <PrintNotes>;
        e.Args = <WriteNote e.Args>;
    };
};

ArgList {
    = <ArgList 1>;
    s.N, <Arg s.N>: {
        = ;
        e.Arg = (e.Arg) <ArgList <+ s.N 1>>;
    };
};

PrintNotes {
    , <ExistFile 'notes.txt'>: {
        False = ;
        True = <PrintFile 1 'notes.txt'>;
    };
};

PrintFile {
    s.Chan e.File = <Open 'r' s.Chan e.File> <PrintFile (s.Chan)>;
    (s.Chan), <Get s.Chan>: {
        0 = <Close s.Chan>;
        e.Line = <Prout e.Line> <PrintFile (s.Chan)>;
    };
};

WriteNote {
    e.Args, <Time> '\n\t' <Join (' ') e.Args> '\n': e.Note =
        <Open 'a' 2 'notes.txt'>
        <Put 2 e.Note>
        <Close 2>;
};

Join {
    (e.X) = ;
    (e.X) (e.1) = e.1;
    (e.X) (e.1) e.2 = e.1 e.X <Join (e.X) e.2>;
};
Output:
$ ls notes.*
notes.ref  notes.rsl
$ refgo notes
$ refgo notes This is a note
$ refgo notes This is another note
$ refgo notes Note that this is a note
$ refgo notes
Mon Apr 8 13:57:34 2024
        This is a note

Mon Apr 8 13:57:38 2024
        This is another note

Mon Apr 8 13:57:42 2024
        Note that this is a note

$ ls notes.*
notes.ref  notes.rsl  notes.txt
$

REXX

/*REXX program implements the "NOTES" command (append text to a file from the C.L.). */
notes = 'notes.txt'                           /*the  fileID  of the  'notes'  file.  */
Select
  When arg(1)='?' Then Do
    Say "'rexx notes text' appends text to file" notes
    Say "'rexx notes' displays file" notes
    End
  When arg()==0  Then Do                      /*No arguments?  Then display the file.*/
    Do while lines(notes)>0
      Say linein(notes)                       /* display a line of file --> screen.  */
      End
    End
  Otherwise Do
    timestamp=right(date(),11,0) time() date('W') /*create current date & time stamp */
    If 'f2'x==2  Then tab='05'x               /* this is an EBCDIC system.           */
                 Else tab='09'x               /*  "   "  "  ASCII    "               */
    Call lineout notes,timestamp              /*append the timestamp to "notes" file.*/
    Call lineout notes,tab||arg(1)            /*   "    "     text    "    "      "  */
    End
  End                                         /*stick a fork in it,  we're all Done. */
Output:
K:\>rexx notes ?
'rexx notes text' appends text to file notes.txt
'rexx notes' displays file notes.txt

K:\>rexx notes starting work

07 Aug 2023 19:39:41 Monday
        starting work

RPL

The file is idiomatically named Logbook rather than NOTES.TXT.

« IFERR Logbook THEN "" END
  IF DEPTH 1 > THEN "\n" + DATE TIME TSTR + END
  WHILE DEPTH 1 > REPEAT "\n" + DEPTH ROLL + END
  DUP 'Logbook' STO
  1 DISP 7 FREEZE
» 'NOTES' STO

Ruby

notes = 'NOTES.TXT'
if ARGV.empty?
  File.copy_stream(notes, $stdout) rescue nil
else
  File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}
end

Rust

This uses version 0.4 of the chrono crate

extern crate chrono;

use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::env;

const FILENAME: &str = "NOTES.TXT";

fn show_notes() -> Result<(), io::Error> {
    let file = OpenOptions::new()
        .read(true)
        .create(true) // create the file if not found
        .write(true) // necessary to create the file
        .open(FILENAME)?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;
    println!("{}", contents);
    Ok(())
}

fn add_to_notes(note: &str) -> Result<(), io::Error> {
    let file = OpenOptions::new()
        .append(true) // disables overwriting, writes to the end of the file
        .create(true)
        .open(FILENAME)?;
    let mut buf_writer = BufWriter::new(file);

    let date_and_time = chrono::Local::now();
    writeln!(buf_writer, "{}", date_and_time)?;

    writeln!(buf_writer, "\t{}", note)
}

fn main() {
    let note = env::args().skip(1).collect::<Vec<_>>();

    if note.is_empty() {
        show_notes().expect("failed to print NOTES.TXT");
    } else {
        add_to_notes(&note.join(" ")).expect("failed to write to NOTES.TXT");
    }
}

Scala

Library: Scala
import java.io.{ FileNotFoundException, FileOutputStream, PrintStream }
import java.time.LocalDateTime

object TakeNotes extends App {
  val notesFileName = "notes.txt"
  if (args.length > 0) {
    val ps = new PrintStream(new FileOutputStream(notesFileName, true))
    ps.println(LocalDateTime.now() + args.mkString("\n\t", " ", "."))
    ps.close()
  } else try {
    io.Source.fromFile(notesFileName).getLines().foreach(println) 
  } catch {
    case e: FileNotFoundException => println(e.getLocalizedMessage())
    case e: Throwable => {
      println("Some other exception type:")
      e.printStackTrace()
    }
  }
}

Scheme

(moved from Racket)

Works with: Racket
#lang racket
(require racket/date)
(define *notes* "NOTES.TXT")

(let ([a (vector->list (current-command-line-arguments))])
  (cond
    [(empty? a)
     (with-handlers ([exn:fail? void])
       (call-with-input-file *notes*
         (lambda (fi)
           (copy-port fi (current-output-port)))))
     ]
    [else
     (call-with-output-file *notes*
       (lambda (fo)
         (let ([ln (apply string-append (add-between a " "))]
               [dt (date->string (current-date))])
           (fprintf fo "~a~n\t~a~n" dt ln)))
       #:mode 'text #:exists 'append)
     ]))

Seed7

$ include "seed7_05.s7i";
$ include "getf.s7i";
$ include "time.s7i";

const string: noteFileName is "NOTES.TXT";

const proc: main is func
  local
    var file: note is STD_NULL;
  begin
    if length(argv(PROGRAM)) = 0 then
      # write NOTES.TXT
      write(getf(noteFileName));
    else
      # Write date & time to NOTES.TXT, and then arguments
      note := open(noteFileName, "a");
      if note <> STD_NULL then
        writeln(note, truncToSecond(time(NOW)));
        writeln(note, "\t" <& join(argv(PROGRAM), " "));
        close(note);
      end if;
    end if;
  end func;

SETL

program notes;
    if #command_line = 0 then
        show_notes;
    else
        write_note;
    end if;

show_notes::
    if (notefile := open('notes.txt', 'r')) = om then
        stop;
    end if;

    loop for line in [getline notefile : until eof(notefile)] do
        print(line);
    end loop;

    close(notefile);

write_note::
    notefile := open('notes.txt', 'a');
    note := (+/[' ' + a : a in command_line])(2..);
    puta(notefile, date + '\n\t' + note + '\n');
    close(notefile);
end program;
Output:
$ ls notes.*
notes.setl
$ setl notes.setl
$ setl notes.setl This is a note
$ setl notes.setl This is another note
$ setl notes.setl
Mon Apr  8 14:27:07 2024
        This is a note

Mon Apr  8 14:27:11 2024
        This is another note

$ ls notes.*
notes.setl  notes.txt

Sidef

var file = %f'notes.txt'

if (ARGV.len > 0) {
    var fh = file.open_a
    fh.say(Time.local.ctime + "\n\t" + ARGV.join(" "))
    fh.close
} else {
    var fh = file.open_r
    fh && fh.each { .say }
}
Output:
$ sidef notes.sf Test 1
$ sidef notes.sf Test 2
$ sidef notes.sf
Sat Sep 12 00:19:36 2015
	Test 1
Sat Sep 12 00:19:37 2015
	Test 2

SNOBOL4

Works with: Macro SNOBOL4 in C
#! /usr/local/bin/snobol4 -b
	a = 2 ;* skip '-b' parameter
	notefile = "notes.txt"
while 	args = args host(2,a = a + 1) " "		:s(while)
	ident(args)	:f(append)
noparms	input(.notes,io_findunit(),,notefile)		:s(display)f(end)
display	output = notes					:s(display)
	endfile(notes)					:(end)
append	output(.notes,io_findunit(),"A",notefile)	:f(end)
	notes = date()
	notes = char(9) args
end

Swift

import Foundation

let args = Process.arguments
let manager = NSFileManager()
let currentPath = manager.currentDirectoryPath
var err:NSError?

// Create file if it doesn't exist
if !manager.fileExistsAtPath(currentPath + "/notes.txt") {
    println("notes.txt doesn't exist")
    manager.createFileAtPath(currentPath + "/notes.txt", contents: nil, attributes: nil)
}

// handler is what is used to write to the file
let handler = NSFileHandle(forUpdatingAtPath: currentPath + "/notes.txt")

// Print the file if there are no args
if args.count == 1 {
    let str = NSString(contentsOfFile: currentPath + "/notes.txt", encoding: NSUTF8StringEncoding, error: &err)
    println(str!)
    exit(0)
}

let time = NSDate()
let format = NSDateFormatter()
let timeData = (format.stringFromDate(time) + "\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
format.dateFormat = "yyyy.MM.dd 'at' HH:mm:ss zzz"

// We're writing to the end of the file
handler?.seekToEndOfFile()
handler?.writeData(timeData!)

var str = "\t"
for i in 1..<args.count {
    str += args[i] + " "
}

str += "\n"

let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
handler?.writeData(strData!)
Output:

Example output

2015.01.22 at 14:19:18 EST
	this is a note 
2015.01.22 at 14:19:36 EST
	this is something important 

Tcl

# Make it easier to change the name of the notes file
set notefile notes.txt

if {$argc} {
    # Write a message to the file
    set msg [clock format [clock seconds]]\n\t[join $argv " "]
    set f [open $notefile a]
    puts $f $msg
    close $f
} else {
    # Print the contents of the file
    catch {
	set f [open $notefile]
	fcopy $f stdout
	close $f
    }
}
Output:

after a few runs

Thu Apr 01 19:28:07 BST 2010
	test 1 two three
Thu Apr 01 19:28:49 BST 2010
	TODO: Submit notes.tcl to Rosetta Code

uBasic/4tH

Works with: R4

The lack of built-in high level time and date functions makes it more difficult than necessary, since they have to be implemented by user defined functions.

If Cmd (0) > 1 Then                    ' if there are commandline arguments
  If Set (a, Open ("notes.txt", "a")) < 0 Then
    Print "Cannot write \qnotes.txt\q" ' open the file in "append" mode
    End                                ' on error, issue message and exit
  EndIf
                                       ' write the date and time
  Write a, Show (FUNC(_DateStr (Time ())));" ";Show (FUNC(_TimeStr (Time ())))
  
  Write a, "\t";                       ' prepend with a tab
  For i = 2 To Cmd (0) - 1             ' now write all commandline arguments
    Write a, Show (Cmd (i)); " ";      ' with the exception of the last one
  Next
  
  Write a, Show (Cmd (Cmd (0)))        ' write the last argument
Else                                   ' if no commandline arguments are given
  If Set (a, Open ("notes.txt", "r")) < 0 Then
    Print "Cannot read \qnotes.txt\q"  ' open the file in "read" mode
    End                                ' on error, issue message and exit
  EndIf
  
  Do While Read (a)                    ' read until EOF
    Print Show (Tok (0))               ' show the entire line
  Loop                                 ' and repeat..
EndIf

Close a                                ' finally, close the file
End

_DateStr                               ' convert epoch to date string
  Param (1)
  Local (6)

  a@ = a@ / 86400                      ' just get the number of days since epoch
  b@ = 1970+(a@/365)                   ' ball parking year, will not be accurate!

  d@ = 0
  For c@ = 1972 To b@ - 1 Step 4
    If (((c@%4) = 0) * ((c@%100) # 0)) + ((c@%400) = 0) Then d@ = d@+1
  Next

  b@ = 1970+((a@ - d@)/365)            ' calculating accurate current year by (x - extra leap days)
  e@ = ((a@ - d@)%365)+1               ' if current year is leap, set indicator to 1
  f@ = (((b@%4) = 0) * ((b@%100) # 0)) + ((b@%400) = 0)

  g@ = 0                               ' calculating current month
  For c@ = 0 To 11 Until e@ < (g@+1)
    g@ = g@ + FUNC(_Monthdays (c@, f@))
  Next
                                       ' calculating current date
  g@ = g@ - FUNC(_Monthdays (c@-1, f@))
                                       ' Print a@, d@, e@, f@
Return (Join (Str(b@), FUNC(_Format (c@, "-")), FUNC(_Format (e@ - g@, "-"))))

_TimeStr                               ' convert epoch to time string
  Param (1)
Return (Join(Str((a@%86400)/3600), FUNC(_Format ((a@%3600)/60, ":")), FUNC(_Format (a@%60, ":"))))

_Format    Param (2) : Return (Join (Iif (a@<10, Join(b@, "0"), b@), Str (a@)))
_Monthdays Param (2) : Return (((a@ + (a@<7)) % 2) + 30 - ((2 - b@) * (a@=1)))
Output:
2022-04-02 14:58:57
	This is my first entry.
2022-04-02 14:59:10
	It might be useful one day.
2022-04-02 14:59:27
	Anyways, it seems this task is DONE!

UNIX Shell

Bash version

#
NOTES=$HOME/notes.txt
if [[ $# -eq 0 ]] ; then
  [[ -r  $NOTES ]] && more $NOTES
else
  date >> $NOTES
  echo "  $*" >> $NOTES
fi

"Spoiled Bash kid" version

N=~/notes.txt;[[ $# -gt 0 ]] && { date ; echo " $*"; exit 0; }  >> $N || [[ -r $N ]] && cat $N


Portable version

NOTES=$HOME/notes.txt
if test "x$*" = "x"
then
        if test -r  $NOTES
        then
                more $NOTES
        fi
else
        date >> $NOTES
        echo "  $*" >> $NOTES
fi

Visual Basic .NET

Imports System.IO

Module Notes
    Function Main(ByVal cmdArgs() As String) As Integer
        Try
            If cmdArgs.Length = 0 Then
                Using sr As New StreamReader("NOTES.TXT")
                    Console.WriteLine(sr.ReadToEnd)
                End Using
            Else
                Using sw As New StreamWriter("NOTES.TXT", True)
                    sw.WriteLine(Date.Now.ToString())
                    sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs))
                End Using
            End If
        Catch
        End Try
    End Function
End Module

Wren

Library: Wren-ioutil
Library: Wren-date

An awkward task for Wren-cli which currently has no way of determining the current date and time. We therefore have to ask the user to input it plus the note(s).

import "os" for Process
import "./ioutil" for File, FileUtil
import "./date" for Date

var dateFormatIn  = "yyyy|-|mm|-|dd|+|hh|:|MM"
var dateFormatOut = "yyyy|-|mm|-|dd| |hh|:|MM"
var args = Process.arguments
if (args.count == 0) {
    if (File.exists("NOTES.TXT")) System.print(File.read("NOTES.TXT"))
} else if (args.count == 1) {
    System.print("Enter the current date/time (MM/DD+HH:mm) plus at least one other argument.")
} else {
    var dateTime = Date.parse(args[0], dateFormatIn)
    var note = "\t" + args[1..-1].join(" ") + "\n"
    FileUtil.append("NOTES.TXT", dateTime.format(dateFormatOut) + "\n" + note)
}
Output:

Sample session:

$ wren NOTES.wren 2021:09:29+16:50 my first note
$ wren NOTES.wren 2021:09:29+16:51 my second note
$ wren NOTES.wren
2021-09-29 16:50
	my first note
2021-09-29 16:51
	my second note

XPL0

Checks for unlikely array overflows have been omitted for simplicity.

include xpllib;         \Date and Time routines
int     I, NotesSize, Ch, CmdArgSize;
char    Notes(1_000_000), CmdArg(1000);
[\Read in notes.txt, if it exists
Trap(false);                    \disable abort on errors
FSet(FOpen("notes.txt", 0), ^i);
OpenI(3);
if GetErr = 0 then              \file exists
        [I:= 0;
        while GetErr = 0 do     \GetErr detects end-of-file
                [Notes(I):= ChIn(3);
                I:= I+1;
                ];
        NotesSize:= I-2;        \remove 2 EOFs
        ];
\Get command-line argument, if any, from command line
I:= 0;
loop    [Ch:= ChIn(8);
        if Ch = CR then quit;
        CmdArg(I):= Ch;
        I:= I+1;
        ];
CmdArg(I):= 0;          \terminate string
if I = 0 then           \no args, just display notes.txt
        for I:= 0 to NotesSize-1 do ChOut(0, Notes(I))
else    \open notes.txt for output and append CmdArg
        [FSet(FOpen("notes.txt", 1), ^o);
        OpenO(3);
        for I:= 0 to NotesSize-1 do ChOut(3, Notes(I));
        DateOut(3, GetDosDate);  ChOut(3, ^ );
        TimeOut(3, GetDosTime);  CrLf(3);
        ChOut(3, Tab);  Text(3, CmdArg);  CrLf(3);
        Close(3);
        ];
]
Output:
18-Apr-2022  1:27:14p
        first line 
18-Apr-2022  1:27:30p
        another line 
18-Apr-2022  1:42:02p
        final test 

zkl

File notes.zkl:

const notesName="NOTES.TXT";
args:=vm.arglist;
if (not args) 
   { try{ File(notesName).read(*).text.print(); } catch{println("no file")} }
else{
   f:=File(notesName,"a+");
   f.writeln(Time.Date.ctime(),"\n\t",args.concat(" "));
   f.close();
}
Output:
$ zkl notes
no file
$ zkl notes this is a test
$ zkl notes
Tue Apr 8 20:51:16 2014
	this is a test