Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in C++ while keeping its functionality equivalent to the MATLAB version.
DS{1}.account='jsmith'; DS{1}.password='x'; DS{1}.UID=1001; DS{1}.GID=1000; DS{1}.fullname='Joe Smith'; DS{1}.office='Room 1007'; DS{1}.extension='(234)555-8917'; DS{1}.homephone='(234)555-0077'; DS{1}.email='jsmith@rosettacode.org'; DS{1}.directory='/home/jsmith'; DS{1}.shell='/bin/bash'; DS{2}.account='jdoe'; DS{2}.password='x'; DS{2}.UID=1002; DS{2}.GID=1000; DS{2}.fullname='Jane Doe'; DS{2}.office='Room 1004'; DS{2}.extension='(234)555-8914'; DS{2}.homephone='(234)555-0044'; DS{2}.email='jdoe@rosettacode.org'; DS{2}.directory='/home/jdoe'; DS{2}.shell='/bin/bash'; function WriteRecord(fid, rec) fprintf(fid," return; end fid = fopen('passwd.txt','w'); WriteRecord(fid,DS{1}); WriteRecord(fid,DS{2}); fclose(fid); new.account='xyz'; new.password='x'; new.UID=1003; new.GID=1000; new.fullname='X Yz'; new.office='Room 1003'; new.extension='(234)555-8913'; new.homephone='(234)555-0033'; new.email='xyz@rosettacode.org'; new.directory='/home/xyz'; new.shell='/bin/bash'; fid = fopen('passwd.txt','a+'); WriteRecord(fid,new); fclose(fid); fid = fopen('passwd.txt','r'); while ~feof(fid) printf(' end; fclose(fid);
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Write the same algorithm in Java as shown in this MATLAB implementation.
DS{1}.account='jsmith'; DS{1}.password='x'; DS{1}.UID=1001; DS{1}.GID=1000; DS{1}.fullname='Joe Smith'; DS{1}.office='Room 1007'; DS{1}.extension='(234)555-8917'; DS{1}.homephone='(234)555-0077'; DS{1}.email='jsmith@rosettacode.org'; DS{1}.directory='/home/jsmith'; DS{1}.shell='/bin/bash'; DS{2}.account='jdoe'; DS{2}.password='x'; DS{2}.UID=1002; DS{2}.GID=1000; DS{2}.fullname='Jane Doe'; DS{2}.office='Room 1004'; DS{2}.extension='(234)555-8914'; DS{2}.homephone='(234)555-0044'; DS{2}.email='jdoe@rosettacode.org'; DS{2}.directory='/home/jdoe'; DS{2}.shell='/bin/bash'; function WriteRecord(fid, rec) fprintf(fid," return; end fid = fopen('passwd.txt','w'); WriteRecord(fid,DS{1}); WriteRecord(fid,DS{2}); fclose(fid); new.account='xyz'; new.password='x'; new.UID=1003; new.GID=1000; new.fullname='X Yz'; new.office='Room 1003'; new.extension='(234)555-8913'; new.homephone='(234)555-0033'; new.email='xyz@rosettacode.org'; new.directory='/home/xyz'; new.shell='/bin/bash'; fid = fopen('passwd.txt','a+'); WriteRecord(fid,new); fclose(fid); fid = fopen('passwd.txt','r'); while ~feof(fid) printf(' end; fclose(fid);
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Please provide an equivalent version of this MATLAB code in Python.
DS{1}.account='jsmith'; DS{1}.password='x'; DS{1}.UID=1001; DS{1}.GID=1000; DS{1}.fullname='Joe Smith'; DS{1}.office='Room 1007'; DS{1}.extension='(234)555-8917'; DS{1}.homephone='(234)555-0077'; DS{1}.email='jsmith@rosettacode.org'; DS{1}.directory='/home/jsmith'; DS{1}.shell='/bin/bash'; DS{2}.account='jdoe'; DS{2}.password='x'; DS{2}.UID=1002; DS{2}.GID=1000; DS{2}.fullname='Jane Doe'; DS{2}.office='Room 1004'; DS{2}.extension='(234)555-8914'; DS{2}.homephone='(234)555-0044'; DS{2}.email='jdoe@rosettacode.org'; DS{2}.directory='/home/jdoe'; DS{2}.shell='/bin/bash'; function WriteRecord(fid, rec) fprintf(fid," return; end fid = fopen('passwd.txt','w'); WriteRecord(fid,DS{1}); WriteRecord(fid,DS{2}); fclose(fid); new.account='xyz'; new.password='x'; new.UID=1003; new.GID=1000; new.fullname='X Yz'; new.office='Room 1003'; new.extension='(234)555-8913'; new.homephone='(234)555-0033'; new.email='xyz@rosettacode.org'; new.directory='/home/xyz'; new.shell='/bin/bash'; fid = fopen('passwd.txt','a+'); WriteRecord(fid,new); fclose(fid); fid = fopen('passwd.txt','r'); while ~feof(fid) printf(' end; fclose(fid);
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Generate a Go translation of this MATLAB snippet without changing its computational steps.
DS{1}.account='jsmith'; DS{1}.password='x'; DS{1}.UID=1001; DS{1}.GID=1000; DS{1}.fullname='Joe Smith'; DS{1}.office='Room 1007'; DS{1}.extension='(234)555-8917'; DS{1}.homephone='(234)555-0077'; DS{1}.email='jsmith@rosettacode.org'; DS{1}.directory='/home/jsmith'; DS{1}.shell='/bin/bash'; DS{2}.account='jdoe'; DS{2}.password='x'; DS{2}.UID=1002; DS{2}.GID=1000; DS{2}.fullname='Jane Doe'; DS{2}.office='Room 1004'; DS{2}.extension='(234)555-8914'; DS{2}.homephone='(234)555-0044'; DS{2}.email='jdoe@rosettacode.org'; DS{2}.directory='/home/jdoe'; DS{2}.shell='/bin/bash'; function WriteRecord(fid, rec) fprintf(fid," return; end fid = fopen('passwd.txt','w'); WriteRecord(fid,DS{1}); WriteRecord(fid,DS{2}); fclose(fid); new.account='xyz'; new.password='x'; new.UID=1003; new.GID=1000; new.fullname='X Yz'; new.office='Room 1003'; new.extension='(234)555-8913'; new.homephone='(234)555-0033'; new.email='xyz@rosettacode.org'; new.directory='/home/xyz'; new.shell='/bin/bash'; fid = fopen('passwd.txt','a+'); WriteRecord(fid,new); fclose(fid); fid = fopen('passwd.txt','r'); while ~feof(fid) printf(' end; fclose(fid);
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Produce a functionally identical C code for the snippet given in Nim.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Convert this Nim block to C#, preserving its control flow and logic.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Write the same code in C++ as shown below in Nim.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Change the programming language of this snippet from Nim to Java without modifying what it does.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Produce a language-to-language conversion: from Nim to Python, same semantics.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Produce a language-to-language conversion: from Nim to VB, same semantics.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Generate an equivalent Go version of this Nim code.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Maintain the same structure and functionality when rewriting this code in C.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Can you help me rewrite this code in C# instead of Pascal, keeping it the same logically?
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Transform the following Pascal implementation into C++, maintaining the same output and logic.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Rewrite this program in Java while keeping its functionality equivalent to the Pascal version.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Rewrite this program in Python while keeping its functionality equivalent to the Pascal version.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Port the provided Pascal code into VB while preserving the original functionality.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Write a version of this Pascal function in Go with identical behavior.
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Write a version of this Perl function in C with identical behavior.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Port the following code from Perl to C# with equivalent syntax and logic.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Produce a functionally identical C++ code for the snippet given in Perl.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Preserve the algorithm and functionality while converting the code from Perl to Java.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Transform the following Perl implementation into Python, maintaining the same output and logic.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Write the same code in VB as shown below in Perl.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Convert this Perl snippet to Go and keep its semantics consistent.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Write the same algorithm in C as shown in this PowerShell implementation.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Produce a language-to-language conversion: from PowerShell to C#, same semantics.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Please provide an equivalent version of this PowerShell code in C++.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Keep all operations the same but rewrite the snippet in Java.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Generate a Python translation of this PowerShell snippet without changing its computational steps.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Translate the given PowerShell code snippet into VB without altering its behavior.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Change the programming language of this snippet from PowerShell to Go without modifying what it does.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Generate a C translation of this Racket snippet without changing its computational steps.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Change the programming language of this snippet from Racket to C# without modifying what it does.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Preserve the algorithm and functionality while converting the code from Racket to C++.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Maintain the same structure and functionality when rewriting this code in Java.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Maintain the same structure and functionality when rewriting this code in Python.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Convert the following code from Racket to VB, ensuring the logic remains intact.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Keep all operations the same but rewrite the snippet in Go.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Generate a C translation of this COBOL snippet without changing its computational steps.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Produce a functionally identical C# code for the snippet given in COBOL.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Ensure the translated C++ code behaves exactly like the original COBOL snippet.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Change the following COBOL code into Java without altering its purpose.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Rewrite this program in Python while keeping its functionality equivalent to the COBOL version.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Write the same algorithm in VB as shown in this COBOL implementation.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Maintain the same structure and functionality when rewriting this code in Go.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Generate a C translation of this REXX snippet without changing its computational steps.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Convert this REXX snippet to C# and keep its semantics consistent.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Maintain the same structure and functionality when rewriting this code in C++.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Convert this REXX block to Java, preserving its control flow and logic.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Write the same algorithm in Python as shown in this REXX implementation.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Maintain the same structure and functionality when rewriting this code in VB.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Produce a language-to-language conversion: from REXX to Go, same semantics.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Ensure the translated C code behaves exactly like the original Ruby snippet.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Write the same code in C# as shown below in Ruby.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Can you help me rewrite this code in C++ instead of Ruby, keeping it the same logically?
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Transform the following Ruby implementation into Java, maintaining the same output and logic.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Translate the given Ruby code snippet into Python without altering its behavior.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Change the following Ruby code into VB without altering its purpose.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Convert this Ruby block to Go, preserving its control flow and logic.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Ensure the translated C code behaves exactly like the original Scala snippet.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Change the following Scala code into C# without altering its purpose.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Write the same code in C++ as shown below in Scala.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Preserve the algorithm and functionality while converting the code from Scala to Java.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Keep all operations the same but rewrite the snippet in Python.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Convert this Scala block to VB, preserving its control flow and logic.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Translate this program into Go but keep the logic exactly as in Scala.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Generate an equivalent C version of this Tcl code.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
Please provide an equivalent version of this Tcl code in C#.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
using System; using System.IO; namespace AppendPwdRosetta { class PasswordRecord { public string account, password, fullname, office, extension, homephone, email, directory, shell; public int UID, GID; public PasswordRecord(string account, string password, int UID, int GID, string fullname, string office, string extension, string homephone, string email, string directory, string shell) { this.account = account; this.password = password; this.UID = UID; this.GID = GID; this.fullname = fullname; this.office = office; this.extension = extension; this.homephone = homephone; this.email = email; this.directory = directory; this.shell = shell; } public override string ToString() { var gecos = string.Join(",", new string[] { fullname, office, extension, homephone, email }); return string.Join(":", new string[] { account, password, UID.ToString(), GID.ToString(), gecos, directory, shell }); } } class Program { static void Main(string[] args) { var jsmith = new PasswordRecord("jsmith", "x", 1001, 1000, "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", "/home/jsmith", "/bin/bash"); var jdoe = new PasswordRecord("jdoe", "x", 1002, 1000, "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", "/home/jdoe", "/bin/bash"); var xyz = new PasswordRecord("xyz", "x", 1003, 1000, "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", "/home/xyz", "/bin/bash"); File.WriteAllLines("passwd.txt", new string[] { jsmith.ToString(), jdoe.ToString() }); File.AppendAllText("passwd.txt", xyz.ToString()); string[] lines = File.ReadAllLines("passwd.txt"); Console.WriteLine("Appended record: " + lines[2]); } } }
Transform the following Tcl implementation into C++, maintaining the same output and logic.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
#include <iostream> #include <fstream> #include <string> #include <vector> std::ostream& operator<<(std::ostream& out, const std::string s) { return out << s.c_str(); } struct gecos_t { std::string fullname, office, extension, homephone, email; friend std::ostream& operator<<(std::ostream&, const gecos_t&); }; std::ostream& operator<<(std::ostream& out, const gecos_t& g) { return out << g.fullname << ',' << g.office << ',' << g.extension << ',' << g.homephone << ',' << g.email; } struct passwd_t { std::string account, password; int uid, gid; gecos_t gecos; std::string directory, shell; passwd_t(const std::string& a, const std::string& p, int u, int g, const gecos_t& ge, const std::string& d, const std::string& s) : account(a), password(p), uid(u), gid(g), gecos(ge), directory(d), shell(s) { } friend std::ostream& operator<<(std::ostream&, const passwd_t&); }; std::ostream& operator<<(std::ostream& out, const passwd_t& p) { return out << p.account << ':' << p.password << ':' << p.uid << ':' << p.gid << ':' << p.gecos << ':' << p.directory << ':' << p.shell; } std::vector<passwd_t> passwd_list{ { "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" } }; int main() { std::ofstream out_fd("passwd.txt"); for (size_t i = 0; i < passwd_list.size(); ++i) { out_fd << passwd_list[i] << '\n'; } out_fd.close(); out_fd.open("passwd.txt", std::ios::app); out_fd << passwd_t("xyz", "x", 1003, 1000, { "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org" }, "/home/xyz", "/bin/bash") << '\n'; out_fd.close(); std::ifstream in_fd("passwd.txt"); std::string line, temp; while (std::getline(in_fd, temp)) { if (!temp.empty()) { line = temp; } } if (line.substr(0, 4) == "xyz:") { std::cout << "Appended record: " << line << '\n'; } else { std::cout << "Failed to find the expected record appended.\n"; } return 0; }
Convert this Tcl block to Java, preserving its control flow and logic.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RecordAppender { static class Record { private final String account; private final String password; private final int uid; private final int gid; private final List<String> gecos; private final String directory; private final String shell; public Record(String account, String password, int uid, int gid, List<String> gecos, String directory, String shell) { this.account = requireNonNull(account); this.password = requireNonNull(password); this.uid = uid; this.gid = gid; this.gecos = requireNonNull(gecos); this.directory = requireNonNull(directory); this.shell = requireNonNull(shell); } @Override public String toString() { return account + ':' + password + ':' + uid + ':' + gid + ':' + String.join(",", gecos) + ':' + directory + ':' + shell; } public static Record parse(String text) { String[] tokens = text.split(":"); return new Record( tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]), Arrays.asList(tokens[4].split(",")), tokens[5], tokens[6]); } } public static void main(String[] args) throws IOException { List<String> rawData = Arrays.asList( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" ); List<Record> records = rawData.stream().map(Record::parse).collect(Collectors.toList()); Path tmp = Paths.get("_rosetta", ".passwd"); Files.createDirectories(tmp.getParent()); Files.write(tmp, (Iterable<String>) records.stream().limit(2).map(Record::toString)::iterator); Files.write(tmp, Collections.singletonList(records.get(2).toString()), StandardOpenOption.APPEND); try (Stream<String> lines = Files.lines(tmp)) { lines.map(Record::parse).forEach(System.out::println); } } }
Write the same algorithm in Python as shown in this Tcl implementation.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
passwd_list=[ dict(account='jsmith', password='x', UID=1001, GID=1000, GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', homephone='(234)555-0077', email='jsmith@rosettacode.org'), directory='/home/jsmith', shell='/bin/bash'), dict(account='jdoe', password='x', UID=1002, GID=1000, GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', homephone='(234)555-0044', email='jdoe@rosettacode.org'), directory='/home/jdoe', shell='/bin/bash') ] passwd_fields="account password UID GID GECOS directory shell".split() GECOS_fields="fullname office extension homephone email".split() def passwd_text_repr(passwd_rec): passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) for field in passwd_rec: if not isinstance(passwd_rec[field], str): passwd_rec[field]=`passwd_rec[field]` return ":".join([ passwd_rec[field] for field in passwd_fields ]) passwd_text=open("passwd.txt","w") for passwd_rec in passwd_list: print >> passwd_text,passwd_text_repr(passwd_rec) passwd_text.close() passwd_text=open("passwd.txt","a+") new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', homephone='(234)555-0033', email='xyz@rosettacode.org'), directory='/home/xyz', shell='/bin/bash') print >> passwd_text, passwd_text_repr(new_rec) passwd_text.close() passwd_list=list(open("passwd.txt","r")) if "xyz" in passwd_list[-1]: print "Appended record:",passwd_list[-1][:-1]
Convert this Tcl block to VB, preserving its control flow and logic.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
$Include "Rapidq.inc" dim file as qfilestream dim filename as string dim LogRec as string filename = "C:\Logfile2.txt" file.open(filename, fmCreate) file.writeline "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash" file.writeline "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jsmith:/bin/bash" file.close file.open(filename, fmOpenWrite) file.position = File.size file.writeline "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" file.close file.open (filename, fmOpenRead) while not file.EOF LogRec = File.Readline wend file.close showmessage "Appended record: " + LogRec
Transform the following Tcl implementation into Go, maintaining the same output and logic.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
package main import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type pw struct { account, password string uid, gid uint gecos directory, shell string } type gecos struct { fullname, office, extension, homephone, email string } func (p *pw) encode(w io.Writer) (int, error) { return fmt.Fprintf(w, "%s:%s:%d:%d:%s,%s,%s,%s,%s:%s:%s\n", p.account, p.password, p.uid, p.gid, p.fullname, p.office, p.extension, p.homephone, p.email, p.directory, p.shell) } var p2 = []pw{ {"jsmith", "x", 1001, 1000, gecos{"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, {"jdoe", "x", 1002, 1000, gecos{"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"}, "/home/jsmith", "/bin/bash"}, } var pa = pw{"xyz", "x", 1003, 1000, gecos{"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"} var expected = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913," + "(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" const pfn = "mythical" func main() { writeTwo() appendOneMore() checkResult() } func writeTwo() { f, err := os.Create(pfn) if err != nil { fmt.Println(err) return } defer func() { if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } }() for _, p := range p2 { if _, err = p.encode(f); err != nil { fmt.Println(err) return } } } func appendOneMore() { f, err := os.OpenFile(pfn, os.O_RDWR|os.O_APPEND, 0) if err != nil { fmt.Println(err) return } if _, err := pa.encode(f); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(cErr) } } func checkResult() { b, err := ioutil.ReadFile(pfn) if err != nil { fmt.Println(err) return } if string(bytes.Split(b, []byte{'\n'})[2]) == expected { fmt.Println("append okay") } else { fmt.Println("it didn't work") } }
Preserve the algorithm and functionality while converting the code from Rust to PHP.
use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Result; use std::io::Write; use std::path::Path; #[derive(Eq, PartialEq, Debug)] pub struct PasswordRecord { pub account: String, pub password: String, pub uid: u64, pub gid: u64, pub gecos: Vec<String>, pub directory: String, pub shell: String, } impl PasswordRecord { pub fn new( account: &str, password: &str, uid: u64, gid: u64, gecos: Vec<&str>, directory: &str, shell: &str, ) -> PasswordRecord { PasswordRecord { account: account.to_string(), password: password.to_string(), uid, gid, gecos: gecos.iter().map(|s| s.to_string()).collect(), directory: directory.to_string(), shell: shell.to_string(), } } pub fn to_line(&self) -> String { let gecos = self.gecos.join(","); format!( "{}:{}:{}:{}:{}:{}:{}", self.account, self.password, self.uid, self.gid, gecos, self.directory, self.shell ) } pub fn from_line(line: &str) -> PasswordRecord { let sp: Vec<&str> = line.split(":").collect(); if sp.len() < 7 { panic!("Less than 7 fields found"); } else { let uid = sp[2].parse().expect("Cannot parse uid"); let gid = sp[3].parse().expect("Cannot parse gid"); let gecos = sp[4].split(",").collect(); PasswordRecord::new(sp[0], sp[1], uid, gid, gecos, sp[5], sp[6]) } } } pub fn read_password_file(file_name: &str) -> Result<Vec<PasswordRecord>> { let p = Path::new(file_name); if !p.exists() { Ok(vec![]) } else { let f = OpenOptions::new().read(true).open(p)?; Ok(BufReader::new(&f) .lines() .map(|l| PasswordRecord::from_line(&l.unwrap())) .collect()) } } pub fn overwrite_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> { let f = OpenOptions::new() .create(true) .write(true) .open(file_name)?; write_records(f, recs) } pub fn append_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> { let f = OpenOptions::new() .create(true) .append(true) .open(file_name)?; write_records(f, recs) } fn write_records(f: File, recs: &Vec<PasswordRecord>) -> Result<()> { let mut writer = BufWriter::new(f); for rec in recs { write!(writer, "{}\n", rec.to_line())?; } Ok(()) } fn main(){ let recs1 = vec![ PasswordRecord::new( "jsmith", "x", 1001, 1000, vec![ "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", ], "/home/jsmith", "/bin/bash", ), PasswordRecord::new( "jdoe", "x", 1002, 1000, vec![ "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", ], "/home/jdoe", "/bin/bash", ), ]; overwrite_password_file("passwd", &recs1).expect("cannot write file"); let recs2 = read_password_file("passwd").expect("cannot read file"); println!("Original file:"); for r in recs2 { println!("{}",r.to_line()); } let append0 = vec![PasswordRecord::new( "xyz", "x", 1003, 1000, vec![ "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", ], "/home/xyz", "/bin/bash", )]; append_password_file("passwd", &append0).expect("cannot append to file"); let recs2 = read_password_file("passwd").expect("cannot read file"); println!(""); println!("Appended file:"); for r in recs2 { println!("{}",r.to_line()); } }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Convert the following code from Ada to PHP, ensuring the logic remains intact.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings.Bounded; procedure Main is package data_string is new Ada.Strings.Bounded.Generic_Bounded_Length(80); use data_string; type GCOSE_Rec is record Full_Name : Bounded_String; Office : Bounded_String; Extension : Bounded_String; Homephone : Bounded_String; Email : Bounded_String; end record; type Password_Rec is record Account : Bounded_String; Password : Bounded_String; Uid : Natural; Gid : Natural; GCOSE : GCOSE_Rec; Directory : Bounded_String; Shell : Bounded_String; end record; function To_String(Item : GCOSE_Rec) return String is begin return To_String(Item.Full_Name) & "," & To_String(Item.Office) & "," & To_String(Item.Extension) & "," & To_String(Item.Homephone) & "," & To_String(Item.Email); end To_String; function To_String(Item : Password_Rec) return String is uid_str : string(1..4); gid_str : string(1..4); Temp : String(1..5); begin Temp := Item.Uid'Image; uid_str := Temp(2..5); Temp := Item.Gid'Image; gid_str := Temp(2..5); return To_String(Item.Account) & ":" & To_String(Item.Password) & ":" & uid_str & ":" & gid_str & ":" & To_String(Item.GCOSE) & ":" & To_String(Item.Directory) & ":" & To_String(Item.Shell); end To_String; Pwd_List : array (1..3) of Password_Rec; Filename : String := "password.txt"; The_File : File_Type; Line : String(1..256); Length : Natural; begin Pwd_List(1) := (Account => To_Bounded_String("jsmith"), Password => To_Bounded_String("x"), Uid => 1001, GID => 1000, GCOSE => (Full_Name => To_Bounded_String("Joe Smith"), Office => To_Bounded_String("Room 1007"), Extension => To_Bounded_String("(234)555-8917"), Homephone => To_Bounded_String("(234)555-0077"), email => To_Bounded_String("jsmith@rosettacode.org")), directory => To_Bounded_String("/home/jsmith"), shell => To_Bounded_String("/bin/bash")); Pwd_List(2) := (Account => To_Bounded_String("jdoe"), Password => To_Bounded_String("x"), Uid => 1002, GID => 1000, GCOSE => (Full_Name => To_Bounded_String("Jane Doe"), Office => To_Bounded_String("Room 1004"), Extension => To_Bounded_String("(234)555-8914"), Homephone => To_Bounded_String("(234)555-0044"), email => To_Bounded_String("jdoe@rosettacode.org")), directory => To_Bounded_String("/home/jdoe"), shell => To_Bounded_String("/bin/bash")); Pwd_List(3) := (Account => To_Bounded_String("xyz"), Password => To_Bounded_String("x"), Uid => 1003, GID => 1000, GCOSE => (Full_Name => To_Bounded_String("X Yz"), Office => To_Bounded_String("Room 1003"), Extension => To_Bounded_String("(234)555-8913"), Homephone => To_Bounded_String("(234)555-0033"), email => To_Bounded_String("xyz@rosettacode.org")), directory => To_Bounded_String("/home/xyz"), shell => To_Bounded_String("/bin/bash")); Create(File => The_File, Mode => Out_File, Name => Filename); for I in 1..2 loop Put_Line(File => The_File, Item => To_String(Pwd_List(I))); end loop; Reset(File => The_File, Mode => In_File); while not End_Of_File(The_File) loop Get_Line(File => The_File, Item => Line, Last => Length); Put_Line(Line(1..Length)); end loop; New_Line; Reset(File => The_File, Mode => Append_File); Put_Line(File => The_File, Item => To_String(Pwd_List(3))); Reset(File => The_File, Mode => In_File); while not End_Of_File(The_File) loop Get_Line(File => The_File, Item => Line, Last => Length); Put_Line(Line(1..Length)); end loop; Close(The_File); end Main;
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Translate this program into PHP but keep the logic exactly as in AWK.
BEGIN { fn = "\\etc\\passwd" print("account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell") >fn print("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash") >fn print("jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash") >fn close(fn) show_file("initial file") print("xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash") >>fn close(fn) show_file("file after append") exit(0) } function show_file(desc, nr,rec) { printf("%s:\n",desc) while (getline rec <fn > 0) { nr++ printf("%s\n",rec) } close(fn) printf("%d records\n\n",nr) }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Port the provided Common_Lisp code into PHP while preserving the original functionality.
(defvar *initial_data* (list (list "jsmith" "x" 1001 1000 (list "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash") (list "jdoe" "x" 1002 1000 (list "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash"))) (defvar *insert* (list "xyz" "x" 1003 1000 (list "X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (defun serialize (record delim) (string-right-trim delim (reduce (lambda (a b) (typecase b (list (concatenate 'string a (serialize b ",") delim)) (t (concatenate 'string a (typecase b (integer (write-to-string b)) (t b)) delim)))) record :initial-value ""))) (defun main () (with-open-file (stream "./passwd" :direction :output :if-exists :supersede :if-does-not-exist :create) (loop for x in *initial_data* do (format stream (concatenate 'string (serialize x ":") "~%")))) (with-open-file (stream "./passwd" :direction :output :if-exists :append) (format stream (concatenate 'string (serialize *insert* ":") "~%"))) (with-open-file (stream "./passwd") (when stream (loop for line = (read-line stream nil) while line do (if (search "xyz" line) (format t "Appended record: ~a~%" line)))))) (main)
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Generate an equivalent PHP version of this D code.
class Record { private const string account; private const string password; private const int uid; private const int gid; private const string[] gecos; private const string directory; private const string shell; public this(string account, string password, int uid, int gid, string[] gecos, string directory, string shell) { import std.exception; this.account = enforce(account); this.password = enforce(password); this.uid = uid; this.gid = gid; this.gecos = enforce(gecos); this.directory = enforce(directory); this.shell = enforce(shell); } public void toString(scope void delegate(const(char)[]) sink) const { import std.conv : toTextRange; import std.format : formattedWrite; import std.range : put; sink(account); put(sink, ':'); sink(password); put(sink, ':'); toTextRange(uid, sink); put(sink, ':'); toTextRange(gid, sink); put(sink, ':'); formattedWrite(sink, "%-(%s,%)", gecos); put(sink, ':'); sink(directory); put(sink, ':'); sink(shell); } } public Record parse(string text) { import std.array : split; import std.conv : to; import std.string : chomp; string[] tokens = text.chomp.split(':'); return new Record( tokens[0], tokens[1], to!int(tokens[2]), to!int(tokens[3]), tokens[4].split(','), tokens[5], tokens[6]); } void main() { import std.algorithm : map; import std.file : exists, mkdir; import std.stdio; auto rawData = [ "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" ]; auto records = rawData.map!parse; if (!exists("_rosetta")) { mkdir("_rosetta"); } auto passwd = File("_rosetta/.passwd", "w"); passwd.lock(); passwd.writeln(records[0]); passwd.writeln(records[1]); passwd.unlock(); passwd.close(); passwd.open("_rosetta/.passwd", "a"); passwd.lock(); passwd.writeln(records[2]); passwd.unlock(); passwd.close(); passwd.open("_rosetta/.passwd"); foreach(string line; passwd.lines()) { parse(line).writeln(); } passwd.close(); }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Rewrite the snippet below in PHP so it works the same as the original Delphi code.
uses cTypes, unix; const passwdPath = '/tmp/passwd'; resourceString advisoryLockFailed = 'Error: could not obtain advisory lock'; type GECOS = object fullname: string; office: string; extension: string; homephone: string; email: string; function asString: string; end; entry = object account: string; password: string; UID: cUInt; GID: cUInt; comment: GECOS; directory: string; shell: string; function asString: string; end; function GECOS.asString: string; const separator = ','; begin with self do begin writeStr(result, fullname, separator, office, separator, extension, separator, homephone, separator, email); end; end; function entry.asString: string; const separator = ':'; begin with self do begin writeStr(result, account, separator, password, separator, UID:1, separator, GID:1, separator, comment.asString, separator, directory, separator, shell); end; end; procedure writeEntry(var f: text; const value: entry); begin writeLn(f, value.asString); end; procedure appendEntry(var f: text; const value: entry); begin append(f); writeEntry(f, value); end; var passwd: text; procedure releaseLock; begin inc(exitCode, fpFLock(passwd, lock_un)); end; var user: entry; line: string; begin assign(passwd, passwdPath); reset(passwd); if fpFLock(passwd, lock_ex or lock_NB) <> 0 then begin writeLn(stdErr, advisoryLockFailed); halt(1); end; addExitProc(releaseLock); rewrite(passwd); user.account := 'jsmith'; user.password := 'x'; user.UID := 1001; user.GID := 1000; user.comment.fullname := 'Joe Smith'; user.comment.office := 'Room 1007'; user.comment.extension := '(234)555-8917'; user.comment.homephone := '(234)555-0077'; user.comment.email := 'jsmith@rosettacode.org'; user.directory := '/home/jsmith'; user.shell := '/bin/bash'; appendEntry(passwd, user); with user do begin account := 'jdoe'; password := 'x'; UID := 1002; GID := 1000; with comment do begin fullname := 'Jane Doe'; office := 'Room 1004'; extension := '(234)555-8914'; homephone := '(234)555-0044'; email := 'jdoe@rosettacode.org'; end; directory := '/home/jdoe'; shell := '/bin/bash'; end; appendEntry(passwd, user); close(passwd); with user, user.comment do begin account := 'xyz'; UID := 1003; fullname := 'X Yz'; office := 'Room 1003'; extension := '(234)555-8913'; homephone := '(234)555-0033'; email := 'xyz@rosettacode.org'; directory := '/home/xyz'; end; appendEntry(passwd, user); reset(passwd); while not EOF(passwd) do begin readLn(passwd, line); writeLn(line); end; end.
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Change the programming language of this snippet from Elixir to PHP without modifying what it does.
defmodule Gecos do defstruct [:fullname, :office, :extension, :homephone, :email] defimpl String.Chars do def to_string(gecos) do [:fullname, :office, :extension, :homephone, :email] |> Enum.map_join(",", &Map.get(gecos, &1)) end end end defmodule Passwd do defstruct [:account, :password, :uid, :gid, :gecos, :directory, :shell] defimpl String.Chars do def to_string(passwd) do [:account, :password, :uid, :gid, :gecos, :directory, :shell] |> Enum.map_join(":", &Map.get(passwd, &1)) end end end defmodule Appender do def write(filename) do jsmith = %Passwd{ account: "jsmith", password: "x", uid: 1001, gid: 1000, gecos: %Gecos{ fullname: "Joe Smith", office: "Room 1007", extension: "(234)555-8917", homephone: "(234)555-0077", email: "jsmith@rosettacode.org" }, directory: "/home/jsmith", shell: "/bin/bash" } jdoe = %Passwd{ account: "jdoe", password: "x", uid: 1002, gid: 1000, gecos: %Gecos{ fullname: "Jane Doe", office: "Room 1004", extension: "(234)555-8914", homephone: "(234)555-0044", email: "jdoe@rosettacode.org" }, directory: "/home/jdoe", shell: "/bin/bash" } xyz = %Passwd{ account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: %Gecos{ fullname: "X Yz", office: "Room 1003", extension: "(234)555-8913", homephone: "(234)555-0033", email: "xyz@rosettacode.org" }, directory: "/home/xyz", shell: "/bin/bash" } File.open!(filename, [:write], fn file -> IO.puts(file, jsmith) IO.puts(file, jdoe) end) File.open!(filename, [:append], fn file -> IO.puts(file, xyz) end) IO.puts File.read!(filename) end end Appender.write("passwd.txt")
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Produce a functionally identical PHP code for the snippet given in Fortran.
PROGRAM DEMO TYPE DETAILS CHARACTER*28 FULLNAME CHARACTER*12 OFFICE CHARACTER*16 EXTENSION CHARACTER*16 HOMEPHONE CHARACTER*88 EMAIL END TYPE DETAILS TYPE USERSTUFF CHARACTER*8 ACCOUNT CHARACTER*8 PASSWORD INTEGER*2 UID INTEGER*2 GID TYPE(DETAILS) PERSON CHARACTER*18 DIRECTORY CHARACTER*12 SHELL END TYPE USERSTUFF TYPE(USERSTUFF) NOTE NAMELIST /STUFF/ NOTE INTEGER F,MSG,N MSG = 6 F = 10 OPEN(MSG, DELIM = "QUOTE") Create the file and supply its initial content. OPEN (F, FILE="Staff.txt",STATUS="REPLACE",ACTION="WRITE", 1 DELIM="QUOTE",RECL=666) WRITE (F,*) USERSTUFF("jsmith","x",1001,1000, 1 DETAILS("Joe Smith","Room 1007","(234)555-8917", 2 "(234)555-0077","jsmith@rosettacode.org"), 2 "/home/jsmith","/bin/bash") WRITE (F,*) USERSTUFF("jdoe","x",1002,1000, 1 DETAILS("Jane Doe","Room 1004","(234)555-8914", 2 "(234)555-0044","jdoe@rosettacode.org"), 3 "home/jdoe","/bin/bash") CLOSE (F) Choose the existing file, and append a further record to it. OPEN (F, FILE="Staff.txt",STATUS="OLD",ACTION="WRITE", 1 DELIM="QUOTE",RECL=666,ACCESS="APPEND") NOTE = USERSTUFF("xyz","x",1003,1000, 1 DETAILS("X Yz","Room 1003","(234)555-8193", 2 "(234)555-033","xyz@rosettacode.org"), 3 "/home/xyz","/bin/bash") WRITE (F,*) NOTE CLOSE (F) Chase through the file, revealing what had been written.. OPEN (F, FILE="Staff.txt",STATUS="OLD",ACTION="READ", 1 DELIM="QUOTE",RECL=666) N = 0 10 READ (F,*,END = 20) NOTE N = N + 1 WRITE (MSG,11) N 11 FORMAT (/,"Record ",I0) WRITE (MSG,STUFF) GO TO 10 Closedown. 20 CLOSE (F) END
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Port the provided Groovy code into PHP while preserving the original functionality.
class PasswdRecord { String account, password, directory, shell int uid, gid SourceRecord source private static final fs = ':' private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell'] private static final stringFields = ['account', 'password', 'directory', 'shell'] private static final intFields = ['uid', 'gid'] PasswdRecord(String line = null) { if (!line) return def fields = line.split(fs) if (fields.size() != fieldNames.size()) { throw new IllegalArgumentException( "Passwd record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") } (0..<fields.size()).each { i -> switch (fieldNames[i]) { case stringFields: this[fieldNames[i]] = fields[i]; break case intFields: this[fieldNames[i]] = fields[i] as Integer; break default : this.source = new SourceRecord(fields[i]); break } } } @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } } class SourceRecord { String fullname, office, extension, homephone, email private static final fs = ',' private static final fieldNames = ['fullname', 'office', 'extension', 'homephone', 'email'] SourceRecord(String line = null) { if (!line) return def fields = line.split(fs) if (fields.size() != fieldNames.size()) { throw new IllegalArgumentException( "Source record must have exactly ${fieldNames.size()} '${fs}'-delimited fields") } (0..<fields.size()).each { i -> this[fieldNames[i]] = fields[i] } } @Override String toString() { fieldNames.collect { "${this[it]}${fs}" }.sum()[0..-2] } } def appendNewPasswdRecord = { PasswdRecord pwr = new PasswdRecord().with { p -> (account, password, uid, gid) = ['xyz', 'x', 1003, 1000] source = new SourceRecord().with { s -> (fullname, office, extension, homephone, email) = ['X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'] s } (directory, shell) = ['/home/xyz', '/bin/bash'] p }; new File('passwd.txt').withWriterAppend { w -> w.append(pwr as String) w.append('\r\n') } }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Convert the following code from Haskell to PHP, ensuring the logic remains intact.
import System.IO import Data.List (intercalate) data Gecos = Gecos { fullname :: String , office :: String , extension :: String , homephone :: String , email :: String } data Record = Record { account :: String , password :: String , uid :: Int , gid :: Int , directory :: String , shell :: String , gecos :: Gecos } instance Show Gecos where show (Gecos {..}) = intercalate "," [fullname, office, extension, homephone, email] instance Show Record where show (Record {..}) = intercalate ":" [account, password, show uid, show gid, show gecos, directory, shell] addRecord :: String -> Record -> IO () addRecord path r = appendFile path (show r)
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Maintain the same structure and functionality when rewriting this code in PHP.
require'strings ~system/packages/misc/xenos.ijs' record=: [:|: <@deb;._1@(':',]);._2@do bind '0 :0' passfields=: <;._1':username:password:gid:uid:gecos:home:shell' passrec=: LF,~ [: }.@;@ , ':';"0 (passfields i. {. ) { a:,~ {: R1=: passrec record'' username: jsmith password: x gid: 1001 uid: 1000 gecos: Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org home: /home/jsmith shell: /bin/bash ) R2=: passrec record'' username: jdoe password: x gid: 1002 uid: 1000 gecos: Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org home: /home/jdoe shell: /bin/bash ) R3=: passrec record'' username: xyz password: x gid: 1003 uid: 1000 gecos: X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org home: /home/xyz shell: /bin/bash ) passwd=: <'/tmp/passwd.txt' (R1,R2) fwrite passwd R3 fappend passwd assert 1 e. R3 E. fread passwd
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Generate an equivalent PHP version of this Julia code.
using SHA mutable struct Personnel fullname::String office::String extension::String homephone::String email::String Personnel(ful,off,ext,hom,ema) = new(ful,off,ext,hom,ema) end mutable struct Passwd account::String password::String uid::Int32 gid::Int32 personal::Personnel directory::String shell::String Passwd(acc,pas,uid,gid,per,dir,she) = new(acc,pas,uid,gid,per,dir,she) end function writepasswd(filename, passrecords) if(passrecords isa Array) == false passrecords = [passrecords] end fh = open(filename, "a") for pas in passrecords record = join([pas.account, bytes2hex(sha256(pas.password)), pas.uid, pas.gid, join([pas.personal.fullname, pas.personal.office, pas.personal.extension, pas.personal.homephone, pas.personal.email], ','), pas.directory, pas.shell], ':') write(fh, record, "\n") end close(fh) end const jsmith = Passwd("jsmith","x",1001, 1000, Personnel("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"), "/home/jsmith", "/bin/bash") const jdoe = Passwd("jdoe","x",1002, 1000, Personnel("Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"), "/home/jdoe", "/bin/bash") const xyz = Passwd("xyz","x",1003, 1000, Personnel("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), "/home/xyz", "/bin/bash") const pfile = "pfile.csv" writepasswd(pfile, [jsmith, jdoe]) println("Before last record added, file is:\n$(readstring(pfile))") writepasswd(pfile, xyz) println("After last record added, file is:\n$(readstring(pfile))")
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Translate the given Lua code snippet into PHP without altering its behavior.
function append(tbl,filename) local file,err = io.open(filename, "a") if err then return err end file:write(tbl.account..":") file:write(tbl.password..":") file:write(tbl.uid..":") file:write(tbl.gid..":") for i,v in ipairs(tbl.gecos) do if i>1 then file:write(",") end file:write(v) end file:write(":") file:write(tbl.directory..":") file:write(tbl.shell.."\n") file:close() end local smith = {} smith.account = "jsmith" smith.password = "x" smith.uid = 1001 smith.gid = 1000 smith.gecos = {"Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"} smith.directory = "/home/jsmith" smith.shell = "/bin/bash" append(smith, ".passwd") local doe = {} doe.account = "jdoe" doe.password = "x" doe.uid = 1002 doe.gid = 1000 doe.gecos = {"Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"} doe.directory = "/home/jdoe" doe.shell = "/bin/bash" append(doe, ".passwd") local xyz = {} xyz.account = "xyz" xyz.password = "x" xyz.uid = 1003 xyz.gid = 1000 xyz.gecos = {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"} xyz.directory = "/home/xyz" xyz.shell = "/bin/bash" append(xyz, ".passwd")
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Please provide an equivalent version of this Mathematica code in PHP.
data = <|"account" -> "xyz", "password" -> "x", "UID" -> 1003, "GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003", "extension" -> "(234)555-8913", "homephone" -> "(234)555-0033", "email" -> "xyz@rosettacode.org", "directory" -> "/home/xyz", "shell" -> "/bin/bash"|>; asString[data_] := StringRiffle[ ToString /@ Insert[data /@ {"account", "password", "UID", "GID", "directory", "shell"}, StringRiffle[ data /@ {"fullname", "office", "extension", "homephone", "email"}, ","], 5], ":"]; fname = FileNameJoin[{$TemporaryDirectory, "testfile"}]; str = OpenWrite[fname]; Close[str]; Print["Appended record: " <> asString[data]];
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Maintain the same structure and functionality when rewriting this code in PHP.
DS{1}.account='jsmith'; DS{1}.password='x'; DS{1}.UID=1001; DS{1}.GID=1000; DS{1}.fullname='Joe Smith'; DS{1}.office='Room 1007'; DS{1}.extension='(234)555-8917'; DS{1}.homephone='(234)555-0077'; DS{1}.email='jsmith@rosettacode.org'; DS{1}.directory='/home/jsmith'; DS{1}.shell='/bin/bash'; DS{2}.account='jdoe'; DS{2}.password='x'; DS{2}.UID=1002; DS{2}.GID=1000; DS{2}.fullname='Jane Doe'; DS{2}.office='Room 1004'; DS{2}.extension='(234)555-8914'; DS{2}.homephone='(234)555-0044'; DS{2}.email='jdoe@rosettacode.org'; DS{2}.directory='/home/jdoe'; DS{2}.shell='/bin/bash'; function WriteRecord(fid, rec) fprintf(fid," return; end fid = fopen('passwd.txt','w'); WriteRecord(fid,DS{1}); WriteRecord(fid,DS{2}); fclose(fid); new.account='xyz'; new.password='x'; new.UID=1003; new.GID=1000; new.fullname='X Yz'; new.office='Room 1003'; new.extension='(234)555-8913'; new.homephone='(234)555-0033'; new.email='xyz@rosettacode.org'; new.directory='/home/xyz'; new.shell='/bin/bash'; fid = fopen('passwd.txt','a+'); WriteRecord(fid,new); fclose(fid); fid = fopen('passwd.txt','r'); while ~feof(fid) printf(' end; fclose(fid);
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Convert this Nim snippet to PHP and keep its semantics consistent.
import posix import strutils type Gecos = tuple[fullname, office, extension, homephone, email: string] Record = object account: string password: string uid: int gid: int gecos: Gecos directory: string shell: string proc str(gecos: Gecos): string = result = "(" for name, field in gecos.fieldPairs: result.addSep(", ", 1) result.add(name & ": " & field) result.add(')') proc `$`(gecos: Gecos): string = for field in gecos.fields: result.addSep(",", 0) result.add(field) proc parseGecos(s: string): Gecos = let fields = s.split(",") result = (fields[0], fields[1], fields[2], fields[3], fields[4]) proc str(rec: Record): string = for name, field in rec.fieldPairs: result.add(name & ": ") when typeof(field) is Gecos: result.add(str(field)) else: result.add($field) result.add('\n') proc `$`(rec: Record): string = for field in rec.fields: result.addSep(":", 0) result.add($field) proc parseRecord(line: string): Record = let fields = line.split(":") result.account = fields[0] result.password = fields[1] result.uid = fields[2].parseInt() result.gid = fields[3].parseInt() result.gecos = parseGecos(fields[4]) result.directory = fields[5] result.shell = fields[6] proc getLock(f: File): bool = when defined(posix): var flock = TFlock(l_type: cshort(F_WRLCK), l_whence: cshort(SEEK_SET), l_start: 0, l_len: 0) result = f.getFileHandle().fcntl(F_SETLK, flock.addr) >= 0 else: result = true var pwfile: File const Filename = "passwd" const Data = ["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"] pwfile = open(FileName, fmWrite) for line in Data: pwfile.writeLine(line) pwfile.close() echo "Raw content of initial password file:" echo "-------------------------------------" var records: seq[Record] for line in lines(FileName): echo line records.add(line.parseRecord()) echo "" echo "Structured content of initial password file:" echo "--------------------------------------------" for rec in records: echo str(rec) pwfile = open(Filename, fmAppend) let newRecord = Record(account: "xyz", password: "x", uid: 1003, gid: 1000, gecos: ("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), directory: "/home/xyz", shell: "/bin/bash") echo "Appending new record:" echo "---------------------" echo str(newRecord) if pwfile.getLock(): pwFile.writeLine(newRecord) pwfile.close() else: echo "File is locked. Quitting." pwFile.close() quit(QuitFailure) echo "Raw content of updated password file:" echo "-------------------------------------" for line in lines(FileName): echo line
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Can you help me rewrite this code in PHP instead of Pascal, keeping it the same logically?
program appendARecordToTheEndOfATextFile; var passwd: bindable text; FD: bindingType; begin FD := binding(passwd); FD.name := '/tmp/passwd'; bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not open ', FD.name); halt; end; rewrite(passwd); writeLn(passwd, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash'); writeLn(passwd, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash'); unbind(passwd); bind(passwd, FD); FD := binding(passwd); if not FD.bound then begin writeLn('Error: could not reopen ', FD.name); halt; end; extend(passwd); writeLn(passwd, 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash'); end.
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Write the same algorithm in PHP as shown in this Perl implementation.
use strict; use warnings; use Fcntl qw( :flock SEEK_END ); use constant { RECORD_FIELDS => [qw( account password UID GID GECOS directory shell )], GECOS_FIELDS => [qw( fullname office extension homephone email )], RECORD_SEP => ':', GECOS_SEP => ',', PASSWD_FILE => 'passwd.txt', }; my $records_to_write = [ { account => 'jsmith', password => 'x', UID => 1001, GID => 1000, GECOS => { fullname => 'John Smith', office => 'Room 1007', extension => '(234)555-8917', homephone => '(234)555-0077', email => 'jsmith@rosettacode.org', }, directory => '/home/jsmith', shell => '/bin/bash', }, { account => 'jdoe', password => 'x', UID => 1002, GID => 1000, GECOS => { fullname => 'Jane Doe', office => 'Room 1004', extension => '(234)555-8914', homephone => '(234)555-0044', email => 'jdoe@rosettacode.org', }, directory => '/home/jdoe', shell => '/bin/bash', }, ]; my $record_to_append = { account => 'xyz', password => 'x', UID => 1003, GID => 1000, GECOS => { fullname => 'X Yz', office => 'Room 1003', extension => '(234)555-8913', homephone => '(234)555-0033', email => 'xyz@rosettacode.org', }, directory => '/home/xyz', shell => '/bin/bash', }; sub record_to_string { my $rec = shift; my $sep = shift // RECORD_SEP; my $fields = shift // RECORD_FIELDS; my @ary; for my $field (@$fields) { my $r = $rec->{$field}; die "Field '$field' not found" unless defined $r; push @ary, ( $field eq 'GECOS' ? record_to_string( $r, GECOS_SEP, GECOS_FIELDS ) : $r ); } return join $sep, @ary; } sub write_records_to_file { my $records = shift; my $filename = shift // PASSWD_FILE; open my $fh, '>>', $filename or die "Can't open $filename: $!"; flock( $fh, LOCK_EX ) or die "Can't lock $filename: $!"; seek( $fh, 0, SEEK_END ) or die "Can't seek $filename: $!" ; print $fh record_to_string($_), "\n" for @$records; flock( $fh, LOCK_UN ) or die "Can't unlock $filename: $!"; } write_records_to_file( $records_to_write ); write_records_to_file( [$record_to_append] ); { use Test::Simple tests => 1; open my $fh, '<', PASSWD_FILE or die "Can't open ", PASSWD_FILE, ": $!"; my @lines = <$fh>; chomp @lines; ok( $lines[-1] eq 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash', "Appended record: $lines[-1]" ); }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Maintain the same structure and functionality when rewriting this code in PHP.
function Test-FileLock { Param ( [parameter(Mandatory=$true)] [string] $Path ) $outFile = New-Object System.IO.FileInfo $Path if (-not(Test-Path -Path $Path)) { return $false } try { $outStream = $outFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) if ($outStream) { $outStream.Close() } return $false } catch { return $true } } function New-Record { Param ( [string]$Account, [string]$Password, [int]$UID, [int]$GID, [string]$FullName, [string]$Office, [string]$Extension, [string]$HomePhone, [string]$Email, [string]$Directory, [string]$Shell ) $GECOS = [PSCustomObject]@{ FullName = $FullName Office = $Office Extension = $Extension HomePhone = $HomePhone Email = $Email } [PSCustomObject]@{ Account = $Account Password = $Password UID = $UID GID = $GID GECOS = $GECOS Directory = $Directory Shell = $Shell } } function Import-File { Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) if (-not(Test-Path $Path)) { throw [System.IO.FileNotFoundException] } $header = "Account","Password","UID","GID","GECOS","Directory","Shell" $csv = Import-Csv -Path $Path -Delimiter ":" -Header $header -Encoding ASCII $csv | ForEach-Object { New-Record -Account $_.Account ` -Password $_.Password ` -UID $_.UID ` -GID $_.GID ` -FullName $_.GECOS.Split(",")[0] ` -Office $_.GECOS.Split(",")[1] ` -Extension $_.GECOS.Split(",")[2] ` -HomePhone $_.GECOS.Split(",")[3] ` -Email $_.GECOS.Split(",")[4] ` -Directory $_.Directory ` -Shell $_.Shell } } function Export-File { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $InputObject, [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string] $Path = ".\passwd.txt" ) Begin { if (-not(Test-Path $Path)) { New-Item -Path . -Name $Path -ItemType File | Out-Null } [string]$recordString = "{0}:{1}:{2}:{3}:{4}:{5}:{6}" [string]$gecosString = "{0},{1},{2},{3},{4}" [string[]]$lines = @() [string[]]$file = Get-Content $Path } Process { foreach ($object in $InputObject) { $lines += $recordString -f $object.Account, $object.Password, $object.UID, $object.GID, $($gecosString -f $object.GECOS.FullName, $object.GECOS.Office, $object.GECOS.Extension, $object.GECOS.HomePhone, $object.GECOS.Email), $object.Directory, $object.Shell } } End { foreach ($line in $lines) { if (-not ($line -in $file)) { $line | Out-File -FilePath $Path -Encoding ASCII -Append } } } }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Change the following Racket code into PHP without altering its purpose.
#lang racket (define sample1 '("jsmith" "x" 1001 1000 ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash")) (define sample2 '("jdoe" "x" 1002 1000 ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") "/home/jdoe" "/bin/bash")) (define sample3 '("xyz" "x" 1003 1000 ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") "/home/xyz" "/bin/bash")) (define passwd-file "sexpr-passwd") (define (write-passwds mode . ps) (with-output-to-file passwd-file #:exists mode (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) (define (lookup username) (with-input-from-file passwd-file (λ() (for/first ([p (in-producer read eof)] #:when (equal? username (car p))) p)))) (printf "Creating file with two sample records.\n") (write-passwds 'replace sample1 sample2) (printf "Appending third sample.\n") (write-passwds 'append sample3) (printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz"))
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Translate this program into PHP but keep the logic exactly as in COBOL.
identification division. program-id. append. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select pass-file assign to pass-filename organization is line sequential status is pass-status. REPLACE ==:LRECL:== BY ==2048==. data division. file section. fd pass-file record varying depending on pass-length. 01 fd-pass-record. 05 filler pic x occurs 0 to :LRECL: times depending on pass-length. working-storage section. 01 pass-filename. 05 filler value "passfile". 01 pass-status pic xx. 88 ok-status values '00' thru '09'. 88 eof-pass value '10'. 01 pass-length usage index. 01 total-length usage index. 77 file-action pic x(11). 01 pass-record. 05 account pic x(64). 88 key-account value "xyz". 05 password pic x(64). 05 uid pic z(4)9. 05 gid pic z(4)9. 05 details. 10 fullname pic x(128). 10 office pic x(128). 10 extension pic x(32). 10 homephone pic x(32). 10 email pic x(256). 05 homedir pic x(256). 05 shell pic x(256). 77 colon pic x value ":". 77 comma-mark pic x value ",". 77 newline pic x value x"0a". procedure division. main-routine. perform initial-fill >>IF DEBUG IS DEFINED display "Initial data:" perform show-records >>END-IF perform append-record >>IF DEBUG IS DEFINED display newline "After append:" perform show-records >>END-IF perform verify-append goback . initial-fill. perform open-output-pass-file move "jsmith" to account move "x" to password move 1001 to uid move 1000 to gid move "Joe Smith" to fullname move "Room 1007" to office move "(234)555-8917" to extension move "(234)555-0077" to homephone move "jsmith@rosettacode.org" to email move "/home/jsmith" to homedir move "/bin/bash" to shell perform write-pass-record move "jdoe" to account move "x" to password move 1002 to uid move 1000 to gid move "Jane Doe" to fullname move "Room 1004" to office move "(234)555-8914" to extension move "(234)555-0044" to homephone move "jdoe@rosettacode.org" to email move "/home/jdoe" to homedir move "/bin/bash" to shell perform write-pass-record perform close-pass-file . check-pass-file. if not ok-status then perform file-error end-if . check-pass-with-eof. if not ok-status and not eof-pass then perform file-error end-if . file-error. display "error " file-action space pass-filename space pass-status upon syserr move 1 to return-code goback . append-record. move "xyz" to account move "x" to password move 1003 to uid move 1000 to gid move "X Yz" to fullname move "Room 1003" to office move "(234)555-8913" to extension move "(234)555-0033" to homephone move "xyz@rosettacode.org" to email move "/home/xyz" to homedir move "/bin/bash" to shell perform open-extend-pass-file perform write-pass-record perform close-pass-file . open-output-pass-file. open output pass-file with lock move "open output" to file-action perform check-pass-file . open-extend-pass-file. open extend pass-file with lock move "open extend" to file-action perform check-pass-file . open-input-pass-file. open input pass-file move "open input" to file-action perform check-pass-file . close-pass-file. close pass-file move "closing" to file-action perform check-pass-file . write-pass-record. set total-length to 1 set pass-length to :LRECL: string account delimited by space colon password delimited by space colon trim(uid leading) delimited by size colon trim(gid leading) delimited by size colon trim(fullname trailing) delimited by size comma-mark trim(office trailing) delimited by size comma-mark trim(extension trailing) delimited by size comma-mark trim(homephone trailing) delimited by size comma-mark email delimited by space colon trim(homedir trailing) delimited by size colon trim(shell trailing) delimited by size into fd-pass-record with pointer total-length on overflow display "error: fd-pass-record truncated at " total-length upon syserr end-string set pass-length to total-length set pass-length down by 1 write fd-pass-record move "writing" to file-action perform check-pass-file . read-pass-file. read pass-file move "reading" to file-action perform check-pass-with-eof . show-records. perform open-input-pass-file perform read-pass-file perform until eof-pass perform show-pass-record perform read-pass-file end-perform perform close-pass-file . show-pass-record. display fd-pass-record . verify-append. perform open-input-pass-file move 0 to tally perform read-pass-file perform until eof-pass add 1 to tally unstring fd-pass-record delimited by colon into account if key-account then exit perform end-if perform read-pass-file end-perform if (key-account and tally not > 2) or (not key-account) then display "error: appended record not found in correct position" upon syserr else display "Appended record: " with no advancing perform show-pass-record end-if perform close-pass-file . end program append.
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Produce a functionally identical PHP code for the snippet given in REXX.
tFID= 'PASSWD.TXT' call lineout tFID call writeRec tFID,, 'jsmith',"x", 1001, 1000, 'Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org', "/home/jsmith", '/bin/bash' call writeRec tFID,, 'jdoe', "x", 1002, 1000, 'Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org', "/home/jsmith", '/bin/bash' call lineout fid call writeRec tFID,, 'xyz', "x", 1003, 1000, 'X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org', "/home/xyz", '/bin/bash' call lineout fid exit s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) writeRec: parse arg fid,_ sep=':' do i=3 to arg() _=_ || sep || arg(i) end do tries=0 for 11 r=lineout(fid, _) if r==0 then return call sleep tries end say '***error***'; say r 'record's(r) "not written to file" fid; exit 13
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Produce a language-to-language conversion: from Ruby to PHP, same semantics.
Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s "%s,%s,%s,%s,%s" % to_a end end Passwd = Struct.new(:account, :password, :uid, :gid, :gecos, :directory, :shell) do def to_s to_a.join(':') end end jsmith = Passwd.new('jsmith','x',1001, 1000, Gecos.new('Joe Smith', 'Room 1007', '(234)555-8917', '(234)555-0077', 'jsmith@rosettacode.org'), '/home/jsmith', '/bin/bash') jdoe = Passwd.new('jdoe','x',1002, 1000, Gecos.new('Jane Doe', 'Room 1004', '(234)555-8914', '(234)555-0044', 'jdoe@rosettacode.org'), '/home/jdoe', '/bin/bash') xyz = Passwd.new('xyz','x',1003, 1000, Gecos.new('X Yz', 'Room 1003', '(234)555-8913', '(234)555-0033', 'xyz@rosettacode.org'), '/home/xyz', '/bin/bash') filename = 'append.records.test' File.open(filename, 'w') do |io| io.puts jsmith io.puts jdoe end puts "before appending:" puts File.readlines(filename) File.open(filename, 'a') do |io| io.puts xyz end puts "after appending:" puts File.readlines(filename)
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Convert this Scala snippet to PHP and keep its semantics consistent.
import java.io.File class Record( val account: String, val password: String, val uid: Int, val gid: Int, val gecos: List<String>, val directory: String, val shell: String ){ override fun toString() = "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" } fun parseRecord(line: String): Record { val fields = line.split(':') return Record( fields[0], fields[1], fields[2].toInt(), fields[3].toInt(), fields[4].split(','), fields[5], fields[6] ) } fun main(args: Array<String>) { val startData = listOf( "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" ) val records = startData.map { parseRecord(it) } val f = File("passwd.csv") f.printWriter().use { for (record in records) it.println(record) } println("Initial records:\n") f.forEachLine { println(parseRecord(it)) } val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" val record = parseRecord(newData) if (!f.setWritable(true, true)) { println("\nFailed to make file writable only by owner\n.") } f.appendText("$record\n") println("\nRecords after another one is appended:\n") f.forEachLine { println(parseRecord(it)) } }
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Port the provided Tcl code into PHP while preserving the original functionality.
set basicRecords { { 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/jsmith /bin/bash } } set addedRecords { { xyz x 1003 1000 { {X Yz} {Room 1003} (234)555-8913 (234)555-0033 xyz@rosettacode.org } /home/xyz /bin/bash } } proc printRecords {records fd} { fconfigure $fd -buffering none foreach record $records { lset record 4 [join [lindex $record 4] ","] puts -nonewline $fd [join $record ":"]\n } } proc readRecords fd { set result {} foreach line [split [read $fd] "\n"] { if {$line eq ""} continue set record [split $line ":"] lset record 4 [split [lindex $record 4] ","] lappend result $record } return $result } set f [open ./passwd w] printRecords $basicRecords $f close $f set f [open ./passwd a] printRecords $addedRecords $f close $f set f [open ./passwd] set recs [readRecords $f] close $f puts "last record is for [lindex $recs end 0], named [lindex $recs end 4 0]"
<?php $filename = '/tmp/passwd'; $data = array( 'account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell' . PHP_EOL, 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash' . PHP_EOL, 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' . PHP_EOL, ); file_put_contents($filename, $data, LOCK_EX); echo 'File contents before new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL; $data = array( 'xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash' . PHP_EOL ); file_put_contents($filename, $data, FILE_APPEND | LOCK_EX); echo 'File contents after new record added:', PHP_EOL, file_get_contents($filename), PHP_EOL;
Write the same algorithm in Rust as shown in this C implementation.
#include <stdio.h> #include <string.h> typedef const char *STRING; typedef struct{STRING fullname, office, extension, homephone, email; } gecos_t; typedef struct{STRING account, password; int uid, gid; gecos_t gecos; STRING directory, shell; } passwd_t; #define GECOS_FMT "%s,%s,%s,%s,%s" #define PASSWD_FMT "%s:%s:%d:%d:"GECOS_FMT":%s:%s" passwd_t passwd_list[]={ {"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"} }; main(){ FILE *passwd_text=fopen("passwd.txt", "w"); int rec_num; for(rec_num=0; rec_num < sizeof passwd_list/sizeof(passwd_t); rec_num++) fprintf(passwd_text, PASSWD_FMT"\n", passwd_list[rec_num]); fclose(passwd_text); passwd_text=fopen("passwd.txt", "a+"); char passwd_buf[BUFSIZ]; passwd_t new_rec = {"xyz", "x", 1003, 1000, {"X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"}, "/home/xyz", "/bin/bash"}; sprintf(passwd_buf, PASSWD_FMT"\n", new_rec); write(fileno(passwd_text), passwd_buf, strlen(passwd_buf)); close(passwd_text); passwd_text=fopen("passwd.txt", "r"); while(!feof(passwd_text)) fscanf(passwd_text, "%[^\n]\n", passwd_buf, "\n"); if(strstr(passwd_buf, "xyz")) printf("Appended record: %s\n", passwd_buf); }
use std::fs::File; use std::fs::OpenOptions; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Result; use std::io::Write; use std::path::Path; #[derive(Eq, PartialEq, Debug)] pub struct PasswordRecord { pub account: String, pub password: String, pub uid: u64, pub gid: u64, pub gecos: Vec<String>, pub directory: String, pub shell: String, } impl PasswordRecord { pub fn new( account: &str, password: &str, uid: u64, gid: u64, gecos: Vec<&str>, directory: &str, shell: &str, ) -> PasswordRecord { PasswordRecord { account: account.to_string(), password: password.to_string(), uid, gid, gecos: gecos.iter().map(|s| s.to_string()).collect(), directory: directory.to_string(), shell: shell.to_string(), } } pub fn to_line(&self) -> String { let gecos = self.gecos.join(","); format!( "{}:{}:{}:{}:{}:{}:{}", self.account, self.password, self.uid, self.gid, gecos, self.directory, self.shell ) } pub fn from_line(line: &str) -> PasswordRecord { let sp: Vec<&str> = line.split(":").collect(); if sp.len() < 7 { panic!("Less than 7 fields found"); } else { let uid = sp[2].parse().expect("Cannot parse uid"); let gid = sp[3].parse().expect("Cannot parse gid"); let gecos = sp[4].split(",").collect(); PasswordRecord::new(sp[0], sp[1], uid, gid, gecos, sp[5], sp[6]) } } } pub fn read_password_file(file_name: &str) -> Result<Vec<PasswordRecord>> { let p = Path::new(file_name); if !p.exists() { Ok(vec![]) } else { let f = OpenOptions::new().read(true).open(p)?; Ok(BufReader::new(&f) .lines() .map(|l| PasswordRecord::from_line(&l.unwrap())) .collect()) } } pub fn overwrite_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> { let f = OpenOptions::new() .create(true) .write(true) .open(file_name)?; write_records(f, recs) } pub fn append_password_file(file_name: &str, recs: &Vec<PasswordRecord>) -> Result<()> { let f = OpenOptions::new() .create(true) .append(true) .open(file_name)?; write_records(f, recs) } fn write_records(f: File, recs: &Vec<PasswordRecord>) -> Result<()> { let mut writer = BufWriter::new(f); for rec in recs { write!(writer, "{}\n", rec.to_line())?; } Ok(()) } fn main(){ let recs1 = vec![ PasswordRecord::new( "jsmith", "x", 1001, 1000, vec![ "Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org", ], "/home/jsmith", "/bin/bash", ), PasswordRecord::new( "jdoe", "x", 1002, 1000, vec![ "Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org", ], "/home/jdoe", "/bin/bash", ), ]; overwrite_password_file("passwd", &recs1).expect("cannot write file"); let recs2 = read_password_file("passwd").expect("cannot read file"); println!("Original file:"); for r in recs2 { println!("{}",r.to_line()); } let append0 = vec![PasswordRecord::new( "xyz", "x", 1003, 1000, vec![ "X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org", ], "/home/xyz", "/bin/bash", )]; append_password_file("passwd", &append0).expect("cannot append to file"); let recs2 = read_password_file("passwd").expect("cannot read file"); println!(""); println!("Appended file:"); for r in recs2 { println!("{}",r.to_line()); } }