Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given Tcl code snippet into PHP without altering its behavior.
package require Tcl 8.5 proc binom {n k} { set pTop 1 for {set i $n} {$i > $n - $k} {incr i -1} { set pTop [expr {$pTop * $i}] } set pBottom 1 for {set i $k} {$i > 1} {incr i -1} { set pBottom [expr {$pBottom * $i}] } return [expr {$pTop / $pBottom}] }
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Rewrite this program in Rust while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Convert this C# snippet to Rust and keep its semantics consistent.
using System; namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); } static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; } ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Convert this Java snippet to Rust and keep its semantics consistent.
public class Binomial { private static long binomialInt(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static Object binomialIntReliable(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) { try { binom = Math.multiplyExact(binom, n + 1 - i) / i; } catch (ArithmeticException e) { return "overflow"; } } return binom; } private static double binomialFloat(int n, int k) { if (k > n - k) k = n - k; double binom = 1.0; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static BigInteger binomialBigInt(int n, int k) { if (k > n - k) k = n - k; BigInteger binom = BigInteger.ONE; for (int i = 1; i <= k; i++) { binom = binom.multiply(BigInteger.valueOf(n + 1 - i)); binom = binom.divide(BigInteger.valueOf(i)); } return binom; } private static void demo(int n, int k) { List<Object> data = Arrays.asList( n, k, binomialInt(n, k), binomialIntReliable(n, k), binomialFloat(n, k), binomialBigInt(n, k)); System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t"))); } public static void main(String[] args) { demo(5, 3); demo(1000, 300); } }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Ensure the translated Rust code behaves exactly like the original Go snippet.
package main import "fmt" import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) fmt.Println(new(big.Int).Binomial(60, 30)) }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Port the provided Rust code into Python while preserving the original functionality.
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Rewrite this program in Rust while keeping its functionality equivalent to the C++ version.
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Can you help me rewrite this code in VB instead of Rust, keeping it the same logically?
fn fact(n:u32) -> u64 { let mut f:u64 = n as u64; for i in 2..n { f *= i as u64; } return f; } fn choose(n: u32, k: u32) -> u64 { let mut num:u64 = n as u64; for i in 1..k { num *= (n-i) as u64; } return num / fact(k); } fn main() { println!("{}", choose(5,3)); }
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
Rewrite the snippet below in C# so it works the same as the original Ada code.
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;
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]); } } }
Generate a C translation of this Ada snippet without changing its computational steps.
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;
#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 Ada to C++ without modifying what it does.
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;
#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 Go.
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;
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 code in Java as shown below in Ada.
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;
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 this program into Python but keep the logic exactly as in Ada.
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;
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]
Transform the following Ada implementation into VB, maintaining the same output and logic.
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;
$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 AWK block to C, preserving its control flow and logic.
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) }
#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); }
Ensure the translated C# code behaves exactly like the original AWK snippet.
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) }
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]); } } }
Rewrite this program in C++ while keeping its functionality equivalent to the AWK version.
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) }
#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 AWK block to Java, preserving its control flow and logic.
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) }
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); } } }
Change the following AWK code into Python without altering its purpose.
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) }
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]
Rewrite the snippet below in VB so it works the same as the original AWK code.
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) }
$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 AWK snippet to Go and keep its semantics consistent.
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) }
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") } }
Convert the following code from Common_Lisp to C, ensuring the logic remains intact.
(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)
#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); }
Transform the following Common_Lisp implementation into C#, maintaining the same output and logic.
(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)
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]); } } }
Translate this program into C++ but keep the logic exactly as in Common_Lisp.
(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)
#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 Common_Lisp block to Java, preserving its control flow and logic.
(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)
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.
(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)
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 following code from Common_Lisp to VB with equivalent syntax and logic.
(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)
$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
Port the provided Common_Lisp code into Go 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)
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 language-to-language conversion: from D to C, same semantics.
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(); }
#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 D, keeping it the same logically?
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(); }
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 D implementation into C++, maintaining the same output and logic.
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(); }
#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 D code into Java without altering its purpose.
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(); }
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); } } }
Change the programming language of this snippet from D to Python without modifying what it does.
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(); }
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 D snippet to VB and keep its semantics consistent.
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(); }
$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
Port the following code from D to Go with equivalent syntax and logic.
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(); }
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") } }
Rewrite the snippet below in C 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.
#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 Delphi to C#, same semantics.
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.
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 Delphi, keeping it the same logically?
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.
#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 Delphi snippet to Java and keep its semantics consistent.
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.
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); } } }
Convert this Delphi block to Python, preserving its control flow and logic.
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.
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 VB translation of this Delphi snippet without changing its computational steps.
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.
$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 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.
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 Elixir snippet.
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")
#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 Elixir.
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")
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 Elixir code in C++.
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")
#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.
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")
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 functionally identical Python code for the snippet given in Elixir.
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")
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]
Transform the following Elixir implementation into VB, maintaining the same output and logic.
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")
$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
Can you help me rewrite this code in Go instead of Elixir, keeping it the same logically?
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")
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 Fortran snippet.
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
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 language-to-language conversion: from Fortran to C++, same semantics.
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
#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 C while keeping its functionality equivalent to the Fortran version.
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
#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); }
Maintain the same structure and functionality when rewriting this code in Java.
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
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); } } }
Preserve the algorithm and functionality while converting the code from Fortran to Python.
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
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 Fortran to VB, same semantics.
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
$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
Port the following code from Fortran to PHP with equivalent syntax and logic.
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;
Convert this Groovy block to C, preserving its control flow and logic.
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') } }
#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 Groovy.
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') } }
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 Groovy.
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') } }
#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 Groovy implementation into Java, maintaining the same output and logic.
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') } }
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 this program into Python but keep the logic exactly as in Groovy.
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') } }
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]
Rewrite this program in VB while keeping its functionality equivalent to the Groovy version.
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') } }
$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 Groovy to Go without modifying what it does.
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') } }
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 language-to-language conversion: from Haskell to C, same semantics.
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)
#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 Haskell.
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)
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]); } } }
Convert the following code from Haskell to C++, 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)
#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; }
Port the provided Haskell code into Java while preserving the original functionality.
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)
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); } } }
Change the programming language of this snippet from Haskell to Python without modifying what it does.
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)
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 Haskell code snippet into VB without altering its behavior.
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)
$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 Haskell function in Go with identical behavior.
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)
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") } }
Keep all operations the same but rewrite the snippet in C.
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
#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 J block to C#, preserving its control flow and logic.
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
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 J.
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
#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 code in Java as shown below in J.
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
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 J to Python, same semantics.
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
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 J.
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
$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
Please provide an equivalent version of this J code in Go.
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
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") } }
Convert the following code from Julia to C, ensuring the logic remains intact.
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))")
#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 Julia to C# with equivalent syntax and logic.
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))")
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]); } } }
Port the provided Julia code into C++ while preserving the original functionality.
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))")
#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 Julia code into Java without altering its purpose.
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))")
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 code in Python as shown below in Julia.
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))")
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 Julia block to VB, preserving its control flow and logic.
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))")
$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
Rewrite this program in Go while keeping its functionality equivalent to the Julia version.
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))")
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") } }
Port the following code from Lua to C with equivalent syntax and logic.
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")
#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 a version of this Lua function in C# with identical 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")
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 Lua snippet.
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")
#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; }
Generate an equivalent Java version of this Lua code.
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")
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 Lua code in Python.
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")
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 Lua code into VB without altering its purpose.
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")
$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
Rewrite this program in Go while keeping its functionality equivalent to the Lua version.
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")
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.
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]];
#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); }
Translate this program into C# but keep the logic exactly as in Mathematica.
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]];
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 Mathematica to C++.
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]];
#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; }
Generate a Java translation of this Mathematica snippet without changing its computational steps.
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]];
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); } } }
Convert the following code from Mathematica to Python, ensuring the logic remains intact.
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]];
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 Mathematica code snippet into VB without altering its behavior.
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]];
$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 the following code from Mathematica to Go, ensuring the logic remains intact.
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]];
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") } }
Convert this MATLAB block to C#, preserving its control flow and logic.
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);
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]); } } }