Anonymous user
Append a record to the end of a text file: Difference between revisions
Append a record to the end of a text file (view source)
Revision as of 14:23, 19 February 2024
, 3 months ago→{{header|Sidef}}
(add →Pascal: and →Free Pascal) |
imported>Regattaguru |
||
(8 intermediate revisions by 7 users not shown) | |||
Line 62:
=={{header|Action!}}==
<
CHAR ARRAY header="account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
BYTE dev=[1]
Line 129:
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Append_a_record_to_the_end_of_a_text_file.png Screenshot from Atari 8-bit computer]
Line 146:
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
Line 267:
Close(The_File);
end Main;
</syntaxhighlight>
{{output}}
<pre>
Line 279:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f APPEND_A_RECORD_TO_THE_END_OF_A_TEXT_FILE.AWK
BEGIN {
Line 304:
printf("%d records\n\n",nr)
}
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 322:
=={{header|Batch File}}==
<
@echo off
Line 339:
type append.txt
pause>nul
</syntaxhighlight>
{{out}}
Line 370:
'''From a C "struct" to CSV File'''
<
#include <string.h>
/* note that UID & GID are of type "int" */
Line 422:
if(strstr(passwd_buf, "xyz"))
printf("Appended record: %s\n", passwd_buf);
}</
{{out}}
<pre>
Line 429:
=={{header|C sharp|C#}}==
<
using System.IO;
Line 472:
}
}
</syntaxhighlight>
{{out}}
Line 480:
=={{header|C++}}==
{{trans|C#}}
<
#include <fstream>
#include <string>
Line 560:
return 0;
}</
{{out}}
<pre>Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
Line 611:
'''Record group to passwd format, LINE SEQUENTIAL'''
<syntaxhighlight lang="cobol">
*> Tectonics:
*> cobc -xj append.cob
Line 883:
.
end program append.</
{{out}}
<pre>prompt$ cobc -xj append.cob
Line 891:
=={{header|Common Lisp}}==
Tested on CLISP 2.49
<
(list
(list "jsmith" "x" 1001 1000
Line 943:
(main)
</syntaxhighlight>
{{out}}
<pre>$ clisp append_file.cl
Line 964:
=={{header|D}}==
{{trans|Java}}
<
private const string account;
private const string password;
Line 1,056:
}
passwd.close();
}</
{{out}}
Line 1,077:
| objects (subclass of Struct builtin) || text file || builtin || ☑ || ☑ || ☒
|}
<
defmodule Gecos do
defstruct [:fullname, :office, :extension, :homephone, :email]
Line 1,164:
Appender.write("passwd.txt")
</syntaxhighlight>
{{out}}
<pre>
Line 1,177:
In the absence of a length indication, when outputting text variables with a view to having them read in again, delimiting them with quotes (and doubling internal quotes) is the route to peace of mind, because otherwise a text might contain a comma as in "43 Gurney Road, Belmont" and in the absence of quoting, such a sequence on input might well be taken as two fields rather than one and a mess is certain. This facility is offered by the free-format (or, "list directed") style initiated by the use of * in place of a format label, as in <code>WRITE (MSG,*) ''etc.''</code>, provided however that the output file has been opened with the optional usage attribute <code>DELIM = "QUOTE"</code>, an unfortunate choice of name, because the field separator character could also be termed a "delimiter" and the default value is both a space or comma, when often what is preferable is only a comma, or even a tab. But there is no standard method to specify this desire. Only if the texts never themselves contain commas or spaces will this unquoted free-format scheme evade extra effort, and the specified example precludes this simplicity.
The resulting output is strung along an output line, with a default line length of 132 (a standard lineprinter width); the specification of RECL = 666 ensures that all the output fields are rolled to one line - that isn't padded out to 666 characters: this is not a fixed-length record despite the specification of RECL as a constant, though each record turns out to be 248 characters long. Unfortunately, the trailing spaces in each character variable are rolled forth and there is no option along the lines of <code>WRITE (MSG,*) TRIM(NOTE)</code> One could instead use a suitable FORMAT statement with "A" format codes, but every element of NOTE would have to be named in the output list and the TRIM function applied only to each character field. Not only would this be tedious and error-prone, there is no format code for the enquoting and double-quoting of the texts and thus, no peace of mind... One would of course devise a subroutine to write out such a record (which would probably be more complex, with the FULLNAME subdivided, etc.), but the task's main objective is to demonstrate appending output to a file.<
TYPE DETAILS !Define a component.
CHARACTER*28 FULLNAME
Line 1,240:
Closedown.
20 CLOSE (F)
END</
The output can be read back in with the same free-format style. The fields are separated by spaces (outside a quoted string) though commas are also allowed. The file content is as follows:
Line 1,302:
=={{header|FreeBASIC}}==
<
Type Person
Line 1,387:
Open "passwd.txt" For Append Lock Write As #1
Print #1, records(3)
Close #1</
{{out}}
Line 1,415:
''See also [[#Pascal|Pascal]]''
{{works with|Linux}}
<
{$longStrings on}
{$modeSwitch classicProcVars+}
Line 1,572:
writeLn(line);
end;
end.</
{{out}}
<pre>jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash
Line 1,591:
| <tt>record</tt> || ASCII text || default <abbr title="run-time library">RTL</abbr> || ☑ || ☐ || ☐
|}
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn AppendRecordToFile( pwStr as CFStringRef, url as CFURLRef ) as BOOL
ErrorRef err = NULL
BOOL success = YES
CFDataRef pwData = fn StringData( pwStr, NSUTF8StringEncoding )
FileHandleRef fh = fn FileHandleForWritingToURL( url, @err )
if ( err )
success = fn FileManagerFileExistsAtURL( url )
if success == NO then fn FileManagerCreateFileAtURL( url, pwData, NULL ) : success = YES : exit fn
end if
success = fn FileHandleSeekToEnd( fh, NULL, @err )
if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn
success = fn FileHandleWriteData( fh, pwData, @err )
if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn
success = fn FileHandleClose( fh, @err )
if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn
end fn = success
local fn ReadFileRecords( url as CFURLRef )
ErrorRef err = NULL
CFDataRef pwData = fn DataWithContentsOfURL( url, NSDataReadingMappedIfSafe, @err )
if err then print fn ErrorLocalizedDescription( err ) : exit fn
print fn StringWithData( pwData, NSUTF8StringEncoding )
end fn
local fn ProcessRecords
BOOL success = NO
CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"passwords.txt" )
CFArrayRef pwRecords = @[@"account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell\n",¬
@"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash\n",¬
@"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash\n"]
NSUInteger i, count = len(pwRecords)
for i = 0 to count - 1
success = fn AppendRecordToFile( pwRecords[i], url )
if success then printf @"Record appended to file." else printf @"Failed to append record."
next
fn ReadFileRecords( url )
end fn
fn ProcessRecords
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Record appended to file.
Record appended to file.
Record appended to file.
account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell
jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash
jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash
</pre>
=={{header|Go}}==
<
import (
Line 1,693 ⟶ 1,753:
fmt.Println("it didn't work")
}
}</
{{out}}
<pre>
Line 1,721 ⟶ 1,781:
=={{header|Groovy}}==
Solution:
<
String account, password, directory, shell
int uid, gid
Line 1,788 ⟶ 1,848:
w.append('\r\n')
}
}</
Test:
<
File passwd = new File('passwd.txt')
assert passwd.exists()
Line 1,811 ⟶ 1,871:
println "File contents after new record added"
checkPasswdFile()</
Output:
Line 1,825 ⟶ 1,885:
=={{header|Haskell}}==
Solution:
<
{-# LANGUAGE RecordWildCards #-}
Line 1,855 ⟶ 1,915:
addRecord :: String -> Record -> IO ()
addRecord path r = appendFile path (show r)
</syntaxhighlight>
Test:
<
t1 = Record "jsmith" "x" 1001 1000 "/home/jsmith" "/bin/bash"
(Gecos "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org")
Line 1,873 ⟶ 1,933:
lastLine <- fmap (last . lines) (readFile path)
putStrLn lastLine
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
Works in both languages:
<
orig := [
"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash",
Line 1,889 ⟶ 1,949:
every (f := open(fName,"a")) | write(f,!new) | close(f)
every (f := open(fName,"r")) | write(!f) | close(f)
end</
Run:
Line 1,914 ⟶ 1,974:
=={{header|J}}==
<
record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0'
Line 1,956 ⟶ 2,016:
R3 fappend passwd
assert 1 e. R3 E. fread passwd </
{|class="wikitable" style="text-align: center; margin: 1em auto 1em auto;"
Line 1,971 ⟶ 2,031:
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.IOException;
</syntaxhighlight>
<syntaxhighlight lang="java">
void append(String path, byte[] data) throws IOException {
/* the second argument here is for appending bytes */
try (FileOutputStream output = new FileOutputStream(path, true)) {
output.write(data);
}
}
</syntaxhighlight>
<br />
An alternate implementation.
<syntaxhighlight lang="java">import static java.util.Objects.requireNonNull;
import java.io.IOException;
Line 2,042 ⟶ 2,115:
}
}
}</
{{out}}
<pre>Appended Record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
=={{header|Julia}}==
<
using SHA # security instincts say do not write bare passwords to a shared file even in toy code :)
Line 2,094 ⟶ 2,167:
writepasswd(pfile, xyz)
println("After last record added, file is:\n$(readstring(pfile))")
</syntaxhighlight>
{{output}}<pre>
Before last record added, file is:
Line 2,108 ⟶ 2,181:
=={{header|Kotlin}}==
{{works with|Ubuntu 16.04}}
<
import java.io.File
Line 2,163 ⟶ 2,236:
println(parseRecord(it))
}
}</
{{output}}
Line 2,194 ⟶ 2,267:
=={{header|Lua}}==
<
local file,err = io.open(filename, "a")
if err then return err end
Line 2,245 ⟶ 2,318:
xyz.directory = "/home/xyz"
xyz.shell = "/bin/bash"
append(xyz, ".passwd")</
=={{header|M2000 Interpreter}}==
<
Class passwd {
account$, password$
Line 2,327 ⟶ 2,400:
}
TestThis
</syntaxhighlight>
{{out}}
<pre>
Line 2,336 ⟶ 2,409:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
"GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003",
"extension" -> "(234)555-8913", "homephone" -> "(234)555-0033",
Line 2,352 ⟶ 2,425:
str = OpenWrite[fname]; (* Use OpenAppend if file exists *)
Close[str];
Print["Appended record: " <> asString[data]];</
{{out}}
<pre>Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
Line 2,370 ⟶ 2,443:
=={{header|MATLAB}} / {{header|Octave}}==
<
DS{1}.password='x';
DS{1}.UID=1001;
Line 2,427 ⟶ 2,500:
printf('%s\n',fgetl(fid));
end;
fclose(fid); </
{{out}}
<pre>jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith/bin/bash
Line 2,442 ⟶ 2,515:
As several other solutions, we have chosen to parse the "passwd" lines even if it not required.
<
import strutils
Line 2,589 ⟶ 2,662:
echo "-------------------------------------"
for line in lines(FileName):
echo line</
{{out}}
Line 2,648 ⟶ 2,721:
''See also: [[#Free Pascal|Free Pascal]]''
{{works with|Extended Pascal}}
<
var
Line 2,694 ⟶ 2,767:
{ write another record to file }
writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash');
end.</
{| class="wikitable" style="text-align: center; margin: 1em auto;"
Line 2,712 ⟶ 2,785:
=={{header|Perl}}==
The program uses flock(2) (or emulation, if flock is not available) to lock the file.
<
use warnings;
Line 2,818 ⟶ 2,891:
);
}
</syntaxhighlight>
Output:
Line 2,865 ⟶ 2,938:
same process, in which case locking does not make any real difference - because there is no task_yield() in a locked state.
You can also test the locking when running multiple processes/threads by uncommenting the wait_key() lines.
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o, sleep, task_yield, wait_key)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"passwd.txt"</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span>
<span style="color: #008080;">constant</span>
<span style="color: #000000;">rec1</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"jsmith"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1001</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"Joe Smith"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Room 1007"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-8917"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-0077"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"jsmith@rosettacode.org"</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"/home/jsmith"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"/bin/bash"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">rec2</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"jdoe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1002</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"Jane Doe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Room 1004"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-8914"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-0044"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"jdoe@rosettacode.org"</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"/home/jdoe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"/bin/bash"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">rec3</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"xyz"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1003</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"X Yz"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Room 1003"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-8913"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(234)555-0033"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"xyz@rosettacode.org"</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"/home/xyz"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"/bin/bash"</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">tostring</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">record</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]})</span>
<span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]})</span>
<span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">record</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">],</span><span style="color: #008000;">","</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">record</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">record</span><span style="color: #0000FF;">,</span><span style="color: #008000;">":"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">record</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">wait</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"wait (%s)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">what</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">task_yield</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">file_exists</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</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;">"w"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (someone else just beat us to it?)</span>
<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;">"account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell\n"</span><span style="color: #0000FF;">)</span>
<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;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tostring</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rec1</span><span style="color: #0000FF;">)})</span>
<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;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tostring</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rec2</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</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>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">wait</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"append"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000080;font-style:italic;">--?"file open in append mode"; {} = wait_key()</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">lock_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">LOCK_EXCLUSIVE</span><span style="color: #0000FF;">,{})</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">wait</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"lock"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000080;font-style:italic;">--?"file locked"; {} = wait_key()</span>
<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;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tostring</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rec3</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">unlock_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,{})</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #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;">"r"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">wait</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"read"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">line</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">line</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s:%s:%d:%d:%s:%s:%s\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">],</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">line</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,938 ⟶ 3,014:
=={{header|Phixmonti}}==
<
def ltos /# l -- s #/
Line 2,993 ⟶ 3,069:
endif
endwhile
f fclose</
{{out}}
<pre>["jsmith", "x", "1001", "1000", ["Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"], "/home/jsmith", "/bin/bash"]
Line 3,017 ⟶ 3,093:
|}
<
$filename = '/tmp/passwd';
Line 3,036 ⟶ 3,112:
echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
</syntaxhighlight>
{{out}}
Line 3,051 ⟶ 3,127:
=={{header|PicoLisp}}==
<
"Joe Smith,Room 1007,(234)555-8917,\
(234)555-0077,jsmith@rosettacode.org"
Line 3,077 ⟶ 3,153:
(= 3 (lines "mythical") ) ) ) )
(bye)</
=={{header|PowerShell}}==
Line 3,083 ⟶ 3,159:
Since PowerShell loves to deal in objects I wrote extra code to better manipilate and display data.
<syntaxhighlight lang="powershell">
function Test-FileLock
{
Line 3,247 ⟶ 3,323:
}
}
</syntaxhighlight>
Create record objects.
<syntaxhighlight lang="powershell">
$records = @()
Line 3,275 ⟶ 3,351:
-Directory '/home/jdoe' `
-Shell '/bin/bash'
</syntaxhighlight>
Display record objects.
<syntaxhighlight lang="powershell">
$records | Format-Table -AutoSize
</syntaxhighlight>
{{Out}}
<pre>
Line 3,288 ⟶ 3,364:
</pre>
Export records to file.
<syntaxhighlight lang="powershell">
if (-not(Test-FileLock -Path ".\passwd.txt"))
{
$records | Export-File -Path ".\passwd.txt"
}
</syntaxhighlight>
This is the file.
<syntaxhighlight lang="powershell">
Get-Content -Path ".\passwd.txt"
</syntaxhighlight>
{{Out}}
<pre>
Line 3,304 ⟶ 3,380:
</pre>
Add a record to the record set.
<syntaxhighlight lang="powershell">
$records+= New-Record -Account 'xyz' `
-Password 'x' `
Line 3,316 ⟶ 3,392:
-Directory '/home/xyz' `
-Shell '/bin/bash'
</syntaxhighlight>
Display record objects, sorted on last name; and display them.
<syntaxhighlight lang="powershell">
$records | Sort-Object { $_.GECOS.FullName.Split(" ")[1] } | Format-Table -AutoSize
</syntaxhighlight>
{{Out}}
<pre>
Line 3,330 ⟶ 3,406:
</pre>
Export records to file.
<syntaxhighlight lang="powershell">
if (-not(Test-FileLock -Path ".\passwd.txt"))
{
$records | Export-File -Path ".\passwd.txt"
}
</syntaxhighlight>
This is the file.
<syntaxhighlight lang="powershell">
Get-Content -Path ".\passwd.txt"
</syntaxhighlight>
{{Out}}
<pre>
Line 3,390 ⟶ 3,466:
|}
'''From a "dict" to a CSV File'''
<
# Create a passwd text file
#############################
Line 3,437 ⟶ 3,513:
passwd_list=list(open("passwd.txt","r"))
if "xyz" in passwd_list[-1]:
print "Appended record:",passwd_list[-1][:-1]</
{{out}}
<pre>Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
Line 3,459 ⟶ 3,535:
|}
<
#lang racket
Line 3,496 ⟶ 3,572:
(printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
</syntaxhighlight>
{{out}}
Line 3,512 ⟶ 3,588:
This is kind of silly as it takes a string, converts it to a record, and then instantly converts it back to a string to write out to a file. Most of the "record handling" code is just demonstrating a possible way to store records in memory. It really has nothing to do with appending a string to a file.
<syntaxhighlight lang="raku"
has $.name;
has $.password;
Line 3,578 ⟶ 3,654:
put "Last line of $fname after append:";
put $fname.IO.lines.tail;
</syntaxhighlight>
{{out}}
<pre>Last line of foo.fil before append:
Line 3,616 ⟶ 3,692:
|}
'''The easy short solution'''
<syntaxhighlight lang="vb">
'Short solution: Append record and read last record
$Include "Rapidq.inc"
Line 3,645 ⟶ 3,721:
showmessage "Appended record: " + LogRec
</syntaxhighlight>
{{out}}
<pre>Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
'''Full solution: create an object to handle all functions'''
<syntaxhighlight lang="vb">
'Full solution: Create an object with all required fields and
'build-in functions to append a record and to read the last record
Line 3,796 ⟶ 3,872:
Print ""
input "Press enter to exit:";a$
</syntaxhighlight>
=={{header|REXX}}==
Line 3,814 ⟶ 3,890:
The data fields for the three records were coded on two statements instead of
<br>continuing them on separate statements for brevity.
<
tFID= 'PASSWD.TXT' /*define the name of the output file.*/
call lineout tFID /*close the output file, just in case,*/
Line 3,849 ⟶ 3,925:
say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
/*some error causes: no write access, disk is full, file lockout, no authority*/</
'''PASSWD.TXT''' file before the REXX program ran:
<pre>
Line 3,876 ⟶ 3,952:
| objects (subclass of Struct builtin) || text file || builtin || ☑ || ☑ || ☒
|}
<
class Gecos
def to_s
Line 3,911 ⟶ 3,987:
puts "after appending:"
puts File.readlines(filename)</
{{out}}
<pre>
Line 3,924 ⟶ 4,000:
=={{header|Rust}}==
<
use std::fs::File;
use std::fs::OpenOptions;
Line 4,096 ⟶ 4,172:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,110 ⟶ 4,186:
=={{header|Scala}}==
{{libheader|Scala}}<
import scala.io.Source
Line 4,165 ⟶ 4,241:
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}
} // 57 lines</
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; Join list of strings into single string, with given separator between elements.
(define string-join
(lambda (str-lst sep)
(fold-right (lambda (ele acc) (if (string=? acc "") ele (string-append ele sep acc)))
""
str-lst)))
; Define the output file name and the three records to write to it.
(let ((filename
"mimic-passwd.txt")
(record1
(string-join
(list
"jsmith" "x" "1001" "1000"
(string-join
'("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org")
",")
"/home/jsmith" "/bin/bash")
":"))
(record2
(string-join
(list
"jdoe" "x" "1002" "1000"
(string-join
'("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org")
",")
"/home/jdoe" "/bin/bash")
":"))
(record3
(string-join
(list
"xyz" "x" "1003" "1000"
(string-join
'("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org")
",")
"/home/xyz" "/bin/bash")
":")))
; Write the first two records to the output file.
; Replace any existing file. Lock file for exclusive access.
(let ((op (open-file-output-port filename
(file-options replace exclusive)
'line
(make-transcoder (latin-1-codec) 'lf))))
(format op "~a~%" record1)
(format op "~a~%" record2)
(close-output-port op))
; Append the third record to the output file.
; Open existing file keeping contents. Append to file. Lock file for exclusive access.
(let ((op (open-file-output-port filename
(file-options no-fail no-truncate append exclusive)
'line
(make-transcoder (latin-1-codec) 'lf))))
(format op "~a~%" record3)
(close-output-port op)))</syntaxhighlight>
{{out}}
<pre>
jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash
jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash
xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash
</pre>
{|class="wikitable" style="text-align: center; margin: 1em auto 1em auto;"
|+ Append Capabilities.
|-
!colspan=2| Data Representation
!rowspan=2| IO<BR>Library
!rowspan=2| Append<BR>Possible
!rowspan=2| Automatic<BR>Append
!rowspan=2| Multi-tasking<BR>Safe
|-
! In core || On disk
|-
| lists || text file || built-in || ☑ || ☑ || ☑ (system dependent)
|}
=={{header|Sidef}}==
Line 4,183 ⟶ 4,336:
|}
<
RECORD_FIELDS = %w(account password UID GID GECOS directory shell),
GECOS_FIELDS = %w(fullname office extension homephone email),
Line 4,280 ⟶ 4,433:
'(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash')
say "** Test passed!"</
Note that flock uses advisory lock; some other program (if it doesn't use flock) can still unexpectedly write to the file.
=={{header|Swift}}==
<syntaxhighlight lang="swift">
import Foundation
func appendPasswd(
account: String,
passwd: String,
uid: Int,
gid: Int,
bio: String,
home: String,
shell: String
) {
let str = [
account,
passwd,
String(uid),
String(gid),
bio,
home,
shell
].joined(separator: ":").appending("\n")
guard let data = str.data(using: .utf8) else { return }
let url = URL(fileURLWithPath: "./passwd")
do {
if let fileHandle = try? FileHandle(forWritingTo: url) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
try? fileHandle.close()
} else {
try data.write(to: url)
}
} catch {
print(error)
}
}
</syntaxhighlight>
Usage:
<syntaxhighlight lang="swift">
appendPasswd(
account: "jsmith",
passwd:"x",
uid: 1001,
gid: 1000,
bio: "Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org",
home: "/home/jsmith",
shell: "/bin/bash"
)
</syntaxhighlight>
=={{header|Tcl}}==
Line 4,299 ⟶ 4,501:
|}
Note that appending is only safe on POSIX OSes where the data is written in “small enough” amounts to a local disk. This is a limitation of the OS APIs.
<
set basicRecords {
{
Line 4,383 ⟶ 4,585:
set recs [readRecords $f]
close $f
puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"</
last record is for xyz, named X Yz
The file will have this content:
Line 4,404 ⟶ 4,606:
| one-dimensional arrays (indexed or associative) || text file || builtin (shell redirections) || ☑ || ☑ || OS defined
|}
<
jsmith
x
Line 4,452 ⟶ 4,654:
echo after appending:
cat "$filename"</
{{output}}
Line 4,465 ⟶ 4,667:
=={{header|Ursa}}==
{{trans|Awk}}
<
# create new passwd in working directory
Line 4,492 ⟶ 4,694:
while (f.hasline)
out (in string f) endl console
end while</
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 4,549 ⟶ 4,751:
End Sub
End Module</
{{out}}
<pre>Appended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash</pre>
Line 4,557 ⟶ 4,759:
To append a record to an existing file in a CLI script, a little digging is required as the method to do this (''File.openWithFlags'') is currently undocumented. However, the following works fine.
<
var records = [
Line 4,585 ⟶ 4,787:
contents = File.read(fileName)
System.print("Records after appending new one:\n")
System.print(contents)</
{{out}}
Line 4,617 ⟶ 4,819:
=={{header|Yabasic}}==
<
// If the file does not exist, it will be created.
Line 4,655 ⟶ 4,857:
wend
close #a</
=={{header|zkl}}==
Line 4,672 ⟶ 4,874:
|}
{{trans|Ruby}}
<
gnames=T("fullname","office","extension","homephone","email"),
pnames=T("account","password","uid","gid","gecos","directory","shell");
Line 4,685 ⟶ 4,887:
fcn init(str){ pnames.zipWith(setVar,vm.arglist) }
fcn toString { pnames.apply(setVar).concat(":") }
}</
The class setVar method takes one or two parameters. With two, it sets the named class variable to a value; with one, it gets the var.
If there aren't enough parameters, the missing ones with be set to Void (yeah, poor error checking).
<
p:=str.strip().split(":");
g:=Gecos(p[4].split(",").xplode());
Passwd(p[0,4].xplode(),g,p[5,*].xplode());
}</
The List xplode method pushes the list contents to the parameter list.
<
Gecos("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"),
"/home/jsmith", "/bin/bash");
Line 4,709 ⟶ 4,911:
f.writeln(xyz); f.close();
File(filename).read().text.print(); // print file</
{{out}}
<pre>
Line 4,716 ⟶ 4,918:
xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash
</pre>
{{omit from|EasyLang}}
|