Append a record to the end of a text file: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 62:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">PROC CreateLog(CHAR ARRAY fname)
CHAR ARRAY header="account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell"
BYTE dev=[1]
Line 146:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
Line 279:
 
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">
# syntax: GAWK -f APPEND_A_RECORD_TO_THE_END_OF_A_TEXT_FILE.AWK
BEGIN {
Line 322:
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
 
Line 370:
 
'''From a C "struct" to CSV File'''
<syntaxhighlight lang=C"c">#include <stdio.h>
#include <string.h>
/* note that UID & GID are of type "int" */
Line 429:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.IO;
 
Line 480:
=={{header|C++}}==
{{trans|C#}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <string>
Line 611:
 
'''Record group to passwd format, LINE SEQUENTIAL'''
<syntaxhighlight lang=COBOL"cobol">
*> Tectonics:
*> cobc -xj append.cob
Line 891:
=={{header|Common Lisp}}==
Tested on CLISP 2.49
<syntaxhighlight lang="lisp">(defvar *initial_data*
(list
(list "jsmith" "x" 1001 1000
Line 964:
=={{header|D}}==
{{trans|Java}}
<syntaxhighlight lang=D"d">class Record {
private const string account;
private const string password;
Line 1,077:
| objects (subclass of Struct builtin) || text file || builtin || ☑ || ☑ || ☒
|}
<syntaxhighlight lang="elixir">
defmodule Gecos do
defstruct [:fullname, :office, :extension, :homephone, :email]
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.<syntaxhighlight lang=Fortran"fortran"> PROGRAM DEMO !As per the described task, more or less.
TYPE DETAILS !Define a component.
CHARACTER*28 FULLNAME
Line 1,302:
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Person
Line 1,415:
''See also [[#Pascal|Pascal]]''
{{works with|Linux}}
<syntaxhighlight lang="delphi">{$mode objFPC}
{$longStrings on}
{$modeSwitch classicProcVars+}
Line 1,593:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,721:
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">class PasswdRecord {
String account, password, directory, shell
int uid, gid
Line 1,791:
 
Test:
<syntaxhighlight lang="groovy">def checkPasswdFile = { it ->
File passwd = new File('passwd.txt')
assert passwd.exists()
Line 1,825:
=={{header|Haskell}}==
Solution:
<syntaxhighlight lang="haskell">
{-# LANGUAGE RecordWildCards #-}
 
Line 1,858:
 
Test:
<syntaxhighlight lang="haskell">
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,877:
=={{header|Icon}} and {{header|Unicon}}==
Works in both languages:
<syntaxhighlight lang="unicon">procedure main()
orig := [
"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash",
Line 1,914:
 
=={{header|J}}==
<syntaxhighlight lang="j">require'strings ~system/packages/misc/xenos.ijs'
record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0'
 
Line 1,972:
=={{header|Java}}==
 
<syntaxhighlight lang="java">import static java.util.Objects.requireNonNull;
 
import java.io.IOException;
Line 2,047:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
using SHA # security instincts say do not write bare passwords to a shared file even in toy code :)
 
Line 2,108:
=={{header|Kotlin}}==
{{works with|Ubuntu 16.04}}
<syntaxhighlight lang="scala">// Version 1.2.41
 
import java.io.File
Line 2,194:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">function append(tbl,filename)
local file,err = io.open(filename, "a")
if err then return err end
Line 2,247:
append(xyz, ".passwd")</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">Module TestThis {
Class passwd {
account$, password$
Line 2,336:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">data = <|"account" -> "xyz", "password" -> "x", "UID" -> 1003,
"GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003",
"extension" -> "(234)555-8913", "homephone" -> "(234)555-0033",
Line 2,370:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab"matlab"> DS{1}.account='jsmith';
DS{1}.password='x';
DS{1}.UID=1001;
Line 2,442:
 
As several other solutions, we have chosen to parse the "passwd" lines even if it not required.
<syntaxhighlight lang=Nim"nim">import posix
import strutils
 
Line 2,648:
''See also: [[#Free Pascal|Free Pascal]]''
{{works with|Extended Pascal}}
<syntaxhighlight lang="pascal">program appendARecordToTheEndOfATextFile;
 
var
Line 2,712:
=={{header|Perl}}==
The program uses flock(2) (or emulation, if flock is not available) to lock the file.
<syntaxhighlight lang=Perl"perl">use strict;
use warnings;
 
Line 2,865:
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"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>
Line 2,941:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def ltos /# l -- s #/
Line 3,020:
|}
 
<syntaxhighlight lang=PHP"php"><?php
 
$filename = '/tmp/passwd';
Line 3,054:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(setq L '((jsmith x 1001 1000
"Joe Smith,Room 1007,(234)555-8917,\
(234)555-0077,jsmith@rosettacode.org"
Line 3,086:
 
Since PowerShell loves to deal in objects I wrote extra code to better manipilate and display data.
<syntaxhighlight lang=PowerShell"powershell">
function Test-FileLock
{
Line 3,252:
</syntaxhighlight>
Create record objects.
<syntaxhighlight lang=PowerShell"powershell">
$records = @()
 
Line 3,280:
</syntaxhighlight>
Display record objects.
<syntaxhighlight lang=PowerShell"powershell">
$records | Format-Table -AutoSize
</syntaxhighlight>
Line 3,291:
</pre>
Export records to file.
<syntaxhighlight lang=PowerShell"powershell">
if (-not(Test-FileLock -Path ".\passwd.txt"))
{
Line 3,298:
</syntaxhighlight>
This is the file.
<syntaxhighlight lang=PowerShell"powershell">
Get-Content -Path ".\passwd.txt"
</syntaxhighlight>
Line 3,307:
</pre>
Add a record to the record set.
<syntaxhighlight lang=PowerShell"powershell">
$records+= New-Record -Account 'xyz' `
-Password 'x' `
Line 3,321:
</syntaxhighlight>
Display record objects, sorted on last name; and display them.
<syntaxhighlight lang=PowerShell"powershell">
$records | Sort-Object { $_.GECOS.FullName.Split(" ")[1] } | Format-Table -AutoSize
</syntaxhighlight>
Line 3,333:
</pre>
Export records to file.
<syntaxhighlight lang=PowerShell"powershell">
if (-not(Test-FileLock -Path ".\passwd.txt"))
{
Line 3,340:
</syntaxhighlight>
This is the file.
<syntaxhighlight lang=PowerShell"powershell">
Get-Content -Path ".\passwd.txt"
</syntaxhighlight>
Line 3,393:
|}
'''From a "dict" to a CSV File'''
<syntaxhighlight lang="python">#############################
# Create a passwd text file
#############################
Line 3,462:
|}
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 3,515:
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=perl6"raku" line>class record {
has $.name;
has $.password;
Line 3,619:
|}
'''The easy short solution'''
<syntaxhighlight lang="vb">
'Short solution: Append record and read last record
$Include "Rapidq.inc"
Line 3,653:
 
'''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,817:
The data fields for the three records were coded on two statements instead of
<br>continuing them on separate statements for brevity.
<syntaxhighlight lang="rexx">/*REXX program writes (appends) two records, closes the file, appends another record.*/
tFID= 'PASSWD.TXT' /*define the name of the output file.*/
call lineout tFID /*close the output file, just in case,*/
Line 3,879:
| objects (subclass of Struct builtin) || text file || builtin || ☑ || ☑ || ☒
|}
<syntaxhighlight lang="ruby">Gecos = Struct.new :fullname, :office, :extension, :homephone, :email
class Gecos
def to_s
Line 3,927:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::fs::File;
use std::fs::OpenOptions;
Line 4,113:
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.io.{File, FileWriter, IOException}
import scala.io.Source
 
Line 4,171:
=={{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)
Line 4,263:
|}
 
<syntaxhighlight lang="ruby">define (
RECORD_FIELDS = %w(account password UID GID GECOS directory shell),
GECOS_FIELDS = %w(fullname office extension homephone email),
Line 4,379:
|}
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.
<syntaxhighlight lang="tcl"># Model the data as nested lists, as that is a natural fit for Tcl
set basicRecords {
{
Line 4,484:
| one-dimensional arrays (indexed or associative) || text file || builtin (shell redirections) || ☑ || ☑ || OS defined
|}
<syntaxhighlight lang="bash">rec1=(
jsmith
x
Line 4,545:
=={{header|Ursa}}==
{{trans|Awk}}
<syntaxhighlight lang="ursa"># ursa appends to files by default when the out function is used
 
# create new passwd in working directory
Line 4,576:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.IO
 
Module Module1
Line 4,637:
 
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.
<syntaxhighlight lang="ecmascript">import "io" for File, FileFlags
 
var records = [
Line 4,697:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">a = open("passwd", "a") // Open the file for appending, i.e. what you write to the file will be appended after its initial contents.
// If the file does not exist, it will be created.
Line 4,752:
|}
{{trans|Ruby}}
<syntaxhighlight lang="zkl">var [const]
gnames=T("fullname","office","extension","homephone","email"),
pnames=T("account","password","uid","gid","gecos","directory","shell");
Line 4,768:
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).
<syntaxhighlight lang="zkl">fcn strToPasswd(str){ // blow apart file line to class
p:=str.strip().split(":");
g:=Gecos(p[4].split(",").xplode());
Line 4,774:
}</syntaxhighlight>
The List xplode method pushes the list contents to the parameter list.
<syntaxhighlight lang="zkl">jsmith:=Passwd("jsmith","x",1001, 1000,
Gecos("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"),
"/home/jsmith", "/bin/bash");
10,327

edits