Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in PHP as shown below in AWK.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Change the programming language of this snippet from BBC_Basic to PHP without modifying what it does.
FIFOSIZE = 1000 FOR n = 3 TO 5 PRINT "Push ";n : PROCenqueue(n) NEXT PRINT "Pop " ; FNdequeue PRINT "Push 6" : PROCenqueue(6) REPEAT PRINT "Pop " ; FNdequeue UNTIL FNisempty PRINT "Pop " ; FNdequeue END DEF PROCenqueue(n) : LOCAL f% DEF FNdequeue : LOCAL f% : f% = 1 DEF FNisempty : LOCAL f% : f% = 2 PRIVATE fifo(), rptr%, wptr% DIM fifo(FIFOSIZE-1) CASE f% OF WHEN 0: wptr% = (wptr% + 1) MOD FIFOSIZE IF rptr% = wptr% ERROR 100, "Error: queue overflowed" fifo(wptr%) = n WHEN 1: IF rptr% = wptr% ERROR 101, "Error: queue empty" rptr% = (rptr% + 1) MOD FIFOSIZE = fifo(rptr%) WHEN 2: = (rptr% = wptr%) ENDCASE ENDPROC
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Keep all operations the same but rewrite the snippet in PHP.
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue user=> (empty? @aqueue) true user=> (swap! aqueue conj 1) user=> (swap! aqueue into [2 3 4]) user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (peek @aqueue) 1 user=> (pprint (pop @aqueue)) <-(2 3 4)-< user=> (pprint @aqueue) <-(1 2 3 4)-< user=> (into [] @aqueue) [1 2 3 4] user=> (-> @aqueue rest (conj 5) pprint) (5 2 3 4) user=> (-> @aqueue pop (conj 5) pprint) <-(2 3 4 5)-<
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Change the following Common_Lisp code into PHP without altering its purpose.
(defun enqueue (x xs) (cons x xs)) (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys))))) (defun empty (xs) (endp xs))
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Rewrite this program in PHP while keeping its functionality equivalent to the Delphi version.
program QueueDefinition; uses System.Generics.Collections; type TQueue = System.Generics.Collections.TQueue<Integer>; TQueueHelper = class helper for TQueue function Empty: Boolean; function Pop: Integer; procedure Push(const NewItem: Integer); end; function TQueueHelper.Empty: Boolean; begin Result := count = 0; end; function TQueueHelper.Pop: Integer; begin Result := Dequeue; end; procedure TQueueHelper.Push(const NewItem: Integer); begin Enqueue(NewItem); end; var Queue: TQueue; i: Integer; begin Queue := TQueue.Create; for i := 1 to 1000 do Queue.push(i); while not Queue.Empty do Write(Queue.pop, ' '); Writeln; Queue.Free; Readln; end.
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Change the programming language of this snippet from Elixir to PHP without modifying what it does.
defmodule Queue do def new, do: {Queue, [], []} def push({Queue, input, output}, x), do: {Queue, [x|input], output} def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} def empty?({Queue, [], []}), do: true def empty?({Queue, _, _}), do: false end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Translate the given Erlang code snippet into PHP without altering its behavior.
-module(fifo). -export([new/0, push/2, pop/1, empty/1]). new() -> {fifo, [], []}. push({fifo, In, Out}, X) -> {fifo, [X|In], Out}. pop({fifo, [], []}) -> erlang:error('empty fifo'); pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)}); pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}. empty({fifo, [], []}) -> true; empty({fifo, _, _}) -> false.
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Ensure the translated PHP code behaves exactly like the original Factor snippet.
USING: accessors kernel ; IN: rosetta-code.queue-definition TUPLE: queue head tail ; TUPLE: node value next ; : <queue> ( -- queue ) queue new ; : <node> ( obj -- node ) node new swap >>value ; : empty? ( queue -- ? ) head>> >boolean not ; : enqueue ( obj queue -- ) [ <node> ] dip 2dup dup empty? [ head<< ] [ tail>> next<< ] if tail<< ; : dequeue ( queue -- obj ) dup empty? [ "Cannot dequeue empty queue." throw ] when [ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Preserve the algorithm and functionality while converting the code from Forth to PHP.
1024 constant size create buffer size cells allot here constant end variable head buffer head ! variable tail buffer tail ! variable used 0 used ! : empty? used @ 0= ; : full? used @ size = ; : next cell+ dup end = if drop buffer then ; : put full? abort" buffer full" tail @ ! tail @ next tail ! 1 used +! ; : get empty? abort" buffer empty" head @ @ head @ next head ! -1 used +! ;
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Port the provided Fortran code into PHP while preserving the original functionality.
module FIFO use fifo_nodes type fifo_head type(fifo_node), pointer :: head, tail end type fifo_head contains subroutine new_fifo(h) type(fifo_head), intent(out) :: h nullify(h%head) nullify(h%tail) end subroutine new_fifo subroutine fifo_enqueue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(inout), target :: n if ( associated(h%tail) ) then h%tail%next => n h%tail => n else h%tail => n h%head => n end if nullify(n%next) end subroutine fifo_enqueue subroutine fifo_dequeue(h, n) type(fifo_head), intent(inout) :: h type(fifo_node), intent(out), target :: n if ( associated(h%head) ) then n = h%head if ( associated(n%next) ) then h%head => n%next else nullify(h%head) nullify(h%tail) end if n%valid = .true. else n%valid = .false. end if nullify(n%next) end subroutine fifo_dequeue function fifo_isempty(h) result(r) logical :: r type(fifo_head), intent(in) :: h if ( associated(h%head) ) then r = .false. else r = .true. end if end function fifo_isempty end module FIFO
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Produce a language-to-language conversion: from Groovy to PHP, same semantics.
class Queue { private List buffer public Queue(List buffer = new LinkedList()) { assert buffer != null assert buffer.empty this.buffer = buffer } def push (def item) { buffer << item } final enqueue = this.&push def pop() { if (this.empty) throw new NoSuchElementException('Empty Queue') buffer.remove(0) } final dequeue = this.&pop def getEmpty() { buffer.empty } String toString() { "Queue:${buffer}" } }
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Can you help me rewrite this code in PHP instead of Haskell, keeping it the same logically?
data Fifo a = F [a] [a] emptyFifo :: Fifo a emptyFifo = F [] [] push :: Fifo a -> a -> Fifo a push (F input output) item = F (item:input) output pop :: Fifo a -> (Maybe a, Fifo a) pop (F input (item:output)) = (Just item, F input output) pop (F [] [] ) = (Nothing, F [] []) pop (F input [] ) = pop (F [] (reverse input)) isEmpty :: Fifo a -> Bool isEmpty (F [] []) = True isEmpty _ = False
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Preserve the algorithm and functionality while converting the code from Icon to PHP.
record Queue(items) procedure make_queue () return Queue ([]) end procedure queue_push (queue, item) put (queue.items, item) end procedure queue_pop (queue) return pop (queue.items) end procedure queue_empty (queue) return *queue.items = 0 end procedure main () queue := make_queue() every (item := 1 to 5) do queue_push (queue, item) every (1 to 6) do { write ("Popped value: " || queue_pop (queue)) if (queue_empty (queue)) then write ("empty queue") } end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Translate this program into PHP but keep the logic exactly as in J.
queue_fifo_=: '' pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r ) push_fifo_=: verb define queue=: queue,y y ) isEmpty_fifo_=: verb define 0=#queue )
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Translate this program into PHP but keep the logic exactly as in Julia.
struct Queue{T} a::Array{T,1} end Queue() = Queue(Any[]) Queue(a::DataType) = Queue(a[]) Queue(a) = Queue(typeof(a)[]) Base.isempty(q::Queue) = isempty(q.a) function Base.pop!(q::Queue{T}) where {T} !isempty(q) || error("queue must be non-empty") pop!(q.a) end function Base.push!(q::Queue{T}, x::T) where {T} pushfirst!(q.a, x) return q end function Base.push!(q::Queue{Any}, x::T) where {T} pushfirst!(q.a, x) return q end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Rewrite this program in PHP while keeping its functionality equivalent to the Lua version.
Queue = {} function Queue.new() return { first = 0, last = -1 } end function Queue.push( queue, value ) queue.last = queue.last + 1 queue[queue.last] = value end function Queue.pop( queue ) if queue.first > queue.last then return nil end local val = queue[queue.first] queue[queue.first] = nil queue.first = queue.first + 1 return val end function Queue.empty( queue ) return queue.first > queue.last end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Ensure the translated PHP code behaves exactly like the original Mathematica snippet.
EmptyQ[a_] := Length[a] == 0 SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem] SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Convert this MATLAB snippet to PHP and keep its semantics consistent.
myfifo = {}; myfifo{end+1} = x; x = myfifo{1}; myfifo{1} = []; isempty(myfifo)
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Maintain the same structure and functionality when rewriting this code in PHP.
type Node[T] = ref object value: T next: Node[T] Queue*[T] = object head, tail: Node[T] length: Natural func initQueue*[T](): Queue[T] = Queue[T]() func len*(queue: Queue): Natural = queue.length func isEmpty*(queue: Queue): bool {.inline.} = queue.len == 0 func push*[T](queue: var Queue[T]; value: T) = let node = Node[T](value: value, next: nil) if queue.isEmpty: queue.head = node else: queue.tail.next = node queue.tail = node inc queue.length func pop*[T](queue: var Queue[T]): T = if queue.isEmpty: raise newException(ValueError, "popping from empty queue.") result = queue.head.value queue.head = queue.head.next dec queue.length if queue.isEmpty: queue.tail = nil when isMainModule: var fifo = initQueue[int]() fifo.push(26) fifo.push(99) fifo.push(2) echo "Fifo size: ", fifo.len() try: echo "Popping: ", fifo.pop() echo "Popping: ", fifo.pop() echo "Popping: ", fifo.pop() echo "Popping: ", fifo.pop() except ValueError: echo "Exception catched: ", getCurrentExceptionMsg()
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Translate the given OCaml code snippet into PHP without altering its behavior.
module FIFO : sig type 'a fifo val empty: 'a fifo val push: fifo:'a fifo -> item:'a -> 'a fifo val pop: fifo:'a fifo -> 'a * 'a fifo val is_empty: fifo:'a fifo -> bool end = struct type 'a fifo = 'a list * 'a list let empty = [], [] let push ~fifo:(input,output) ~item = (item::input,output) let is_empty ~fifo = match fifo with | [], [] -> true | _ -> false let rec pop ~fifo = match fifo with | input, item :: output -> item, (input,output) | [], [] -> failwith "empty fifo" | input, [] -> pop ([], List.rev input) end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Ensure the translated PHP code behaves exactly like the original Pascal snippet.
program queue; uses Generics.Collections; var lQueue: TQueue<Integer>; begin lQueue := TQueue<Integer>.Create; try lQueue.EnQueue(1); lQueue.EnQueue(2); lQueue.EnQueue(3); Write(lQueue.DeQueue:2); Write(lQueue.DeQueue:2); Writeln(lQueue.DeQueue:2); Assert(lQueue.Count = 0, 'Queue is not empty'); finally lQueue.Free; end; end.
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Change the following Perl code into PHP without altering its purpose.
use Carp; sub my push :prototype(\@@) {my($list,@things)=@_; push @$list, @things} sub maypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list } sub empty :prototype(@) {not @_}
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Convert this PowerShell block to PHP, preserving its control flow and logic.
$Q = New-Object System.Collections.Queue $Q.Enqueue( 1 ) $Q.Enqueue( 2 ) $Q.Enqueue( 3 ) $Q.Dequeue() $Q.Dequeue() $Q.Count -eq 0 $Q.Dequeue() $Q.Count -eq 0 try { $Q.Dequeue() } catch [System.InvalidOperationException] { If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Change the following R code into PHP without altering its purpose.
empty <- function() length(l) == 0 push <- function(x) { l <<- c(l, list(x)) print(l) invisible() } pop <- function() { if(empty()) stop("can't pop from an empty list") l[[1]] <<- NULL print(l) invisible() } l <- list() empty() push(3) push("abc") push(matrix(1:6, nrow=2)) empty() pop() pop() pop() pop()
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Port the provided Racket code into PHP while preserving the original functionality.
#lang racket (define (make-queue) (mcons #f #f)) (define (push! q x) (define new (mcons x #f)) (if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new)) (set-mcdr! q new)) (define (pop! q) (define old (mcar q)) (cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)] [else (set-mcar! q (mcdr old))]) (mcar old)) (define (empty? q) (not (mcar q))) (define Q (make-queue)) (empty? Q) (push! Q 'x) (empty? Q) (for ([x 3]) (push! Q x)) (pop! Q) (list (pop! Q) (pop! Q) (pop! Q))
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Convert this REXX block to PHP, preserving its control flow and logic.
options replace format comments java crossref savelog symbols nobinary mqueue = ArrayDeque() viewQueue(mqueue) a = "Fred" mqueue.push('') mqueue.push(a 2) viewQueue(mqueue) a = "Toft" mqueue.add(a 2) mqueue.add('') viewQueue(mqueue) loop q_ = 1 while mqueue.size > 0 parse mqueue.pop.toString line say q_.right(3)':' line end q_ viewQueue(mqueue) return method viewQueue(mqueue = Deque) private static If mqueue.size = 0 then do Say 'Queue is empty' end else do Say 'There are' mqueue.size 'elements in the queue' end return
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Ensure the translated PHP code behaves exactly like the original Ruby snippet.
require 'forwardable' class FIFO extend Forwardable def self.[](*objects) new.push(*objects) end def initialize; @ary = []; end def push(*objects) @ary.push(*objects) self end alias << push alias enqueue push def_delegator :@ary, :shift, :pop alias shift pop alias dequeue shift def_delegator :@ary, :empty? def_delegator :@ary, :size alias length size def to_s "FIFO end alias inspect to_s end
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Rewrite this program in PHP while keeping its functionality equivalent to the Scala version.
import java.util.LinkedList class Queue<E> { private val data = LinkedList<E>() val size get() = data.size val empty get() = size == 0 fun push(element: E) = data.add(element) fun pop(): E { if (empty) throw RuntimeException("Can't pop elements from an empty queue") return data.removeFirst() } val top: E get() { if (empty) throw RuntimeException("Empty queue can't have a top element") return data.first() } fun clear() = data.clear() override fun toString() = data.toString() } fun main(args: Array<String>) { val q = Queue<Int>() (1..5).forEach { q.push(it) } println(q) println("Size of queue = ${q.size}") print("Popping: ") (1..3).forEach { print("${q.pop()} ") } println("\nRemaining in queue: $q") println("Top element is now ${q.top}") q.clear() println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}") try { q.pop() } catch (e: Exception) { println(e.message) } }
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Write the same code in PHP as shown below in Tcl.
proc push {stackvar value} { upvar 1 $stackvar stack lappend stack $value } proc pop {stackvar} { upvar 1 $stackvar stack set value [lindex $stack 0] set stack [lrange $stack 1 end] return $value } proc size {stackvar} { upvar 1 $stackvar stack llength $stack } proc empty {stackvar} { upvar 1 $stackvar stack expr {[size stack] == 0} } proc peek {stackvar} { upvar 1 $stackvar stack lindex $stack 0 } set Q [list] empty Q ; push Q foo empty Q ; push Q bar peek Q ; pop Q ; peek Q ;
class Fifo { private $data = array(); public function push($element){ array_push($this->data, $element); } public function pop(){ if ($this->isEmpty()){ throw new Exception('Attempt to pop from an empty queue'); } return array_shift($this->data); } public function enqueue($element) { $this->push($element); } public function dequeue() { return $this->pop(); } public function isEmpty(){ return empty($this->data); } }
Write a version of this C++ function in Rust with identical behavior.
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Can you help me rewrite this code in Rust instead of C#, keeping it the same logically?
public class FIFO<T> { class Node { public T Item { get; set; } public Node Next { get; set; } } Node first = null; Node last = null; public void push(T item) { if (empty()) { first = new Node() { Item = item, Next = null }; last = first; } else { last.Next = new Node() { Item = item, Next = null }; last = last.Next; } } public T pop() { if (first == null) throw new System.Exception("No elements"); if (last == first) last = null; T temp = first.Item; first = first.Next; return temp; } public bool empty() { return first == null; } }
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Write the same algorithm in Python as shown in this Rust implementation.
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
class FIFO(object): def __init__(self, *args): self.contents = list(args) def __call__(self): return self.pop() def __len__(self): return len(self.contents) def pop(self): return self.contents.pop(0) def push(self, item): self.contents.append(item) def extend(self,*itemlist): self.contents += itemlist def empty(self): return bool(self.contents) def __iter__(self): return self def next(self): if self.empty(): raise StopIteration return self.pop() if __name__ == "__main__": f = FIFO() f.push(3) f.push(2) f.push(1) while not f.empty(): print f.pop(), f = FIFO(3,2,1) while not f.empty(): print f(), f = FIFO(3,2,1) while f: print f(), f = FIFO(3,2,1) for i in f: print i,
Transform the following Rust implementation into VB, maintaining the same output and logic.
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Public queue As New Collection Private Sub push(what As Variant) queue.Add what End Sub Private Function pop() As Variant If queue.Count > 0 Then what = queue(1) queue.Remove 1 Else what = CVErr(461) End If pop = what End Function Private Function empty_() empty_ = queue.Count = 0 End Function
Convert this C snippet to Rust and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empty(queue q) { return q->tail == q->head; } void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; if (q->tail == q->alloc) { q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, sizeof(DATA) * (q->alloc - q->head)); q->head += q->alloc; } else q->tail = q->alloc; q->alloc *= 2; } } int dequeue(queue q, DATA *n) { if (q->head == q->tail) return 0; *n = q->buf[q->head++]; if (q->head >= q->alloc) { q->head = 0; if (q->alloc >= 512 && q->tail < q->alloc / 2) q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); } return 1; }
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Write a version of this Go function in Rust with identical behavior.
package queue type Queue struct { b []string head, tail int } func (q *Queue) Push(x string) { switch { case q.tail < 0: next := len(q.b) bigger := make([]string, 2*next) copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head]) bigger[next] = x q.b, q.head, q.tail = bigger, 0, next+1 case len(q.b) == 0: q.b, q.head, q.tail = make([]string, 4), 0 ,1 q.b[0] = x default: q.b[q.tail] = x q.tail++ if q.tail == len(q.b) { q.tail = 0 } if q.tail == q.head { q.tail = -1 } } } func (q *Queue) Pop() (string, bool) { if q.head == q.tail { return "", false } r := q.b[q.head] if q.tail == -1 { q.tail = q.head } q.head++ if q.head == len(q.b) { q.head = 0 } return r, true } func (q *Queue) Empty() bool { return q.head == q.tail }
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Convert the following code from Java to Rust, ensuring the logic remains intact.
public class Queue<E>{ Node<E> head = null, tail = null; static class Node<E>{ E value; Node<E> next; Node(E value, Node<E> next){ this.value= value; this.next= next; } } public Queue(){ } public void enqueue(E value){ Node<E> newNode= new Node<E>(value, null); if(empty()){ head= newNode; }else{ tail.next = newNode; } tail= newNode; } public E dequeue() throws java.util.NoSuchElementException{ if(empty()){ throw new java.util.NoSuchElementException("No more elements."); } E retVal= head.value; head= head.next; return retVal; } public boolean empty(){ return head == null; } }
use std::collections::VecDeque; fn main() { let mut stack = VecDeque::new(); stack.push_back("Element1"); stack.push_back("Element2"); stack.push_back("Element3"); assert_eq!(Some(&"Element1"), stack.front()); assert_eq!(Some("Element1"), stack.pop_front()); assert_eq!(Some("Element2"), stack.pop_front()); assert_eq!(Some("Element3"), stack.pop_front()); assert_eq!(None, stack.pop_front()); }
Produce a language-to-language conversion: from Ada to C#, same semantics.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Rewrite this program in C# while keeping its functionality equivalent to the Ada version.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Port the provided Ada code into C while preserving the original functionality.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Convert this Ada block to C, preserving its control flow and logic.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Transform the following Ada implementation into C++, maintaining the same output and logic.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Preserve the algorithm and functionality while converting the code from Ada to C++.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Generate a Go translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Can you help me rewrite this code in Go instead of Ada, keeping it the same logically?
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Transform the following Ada implementation into Java, maintaining the same output and logic.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Preserve the algorithm and functionality while converting the code from Ada to Java.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Change the programming language of this snippet from Ada to Python without modifying what it does.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Keep all operations the same but rewrite the snippet in Python.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Convert the following code from Ada to VB, ensuring the logic remains intact.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Generate a VB translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO, Ada.Directories, Ada.Command_Line, Ada.IO_Exceptions; use Ada.Text_IO; procedure Remove_Lines_From_File is Temporary: constant String := ".tmp"; begin if Ada.Command_Line.Argument_Count /= 3 then raise Constraint_Error; end if; declare Filename: String := Ada.Command_Line.Argument(1); First: Positive := Integer'Value(Ada.Command_Line.Argument(2)); Last: Natural := Integer'Value(Ada.Command_Line.Argument(3)) + First - 1; Input, Output: File_Type; Line_Number: Positive := 1; begin Open(Input, In_File, Filename); Create(Output, Out_File, Filename & Temporary); while not End_Of_File(Input) loop declare Line: String := Get_Line(Input); begin if Line_Number < First or else Line_Number > Last then Put_Line(Output, Line); end if; end; Line_Number := Line_Number + 1; end loop; Close(Input); Close(Output); Ada.Directories.Rename(Old_Name => Filename & Temporary, New_Name => Filename); end; exception when Constraint_Error | Ada.IO_Exceptions.Name_Error => Put_Line("usage: " & Ada.Command_Line.Command_Name & " <filename> <first> <length>"); Put_Line(" opens <filename> for reading and " & "<filename>" & Temporary & " for temporary writing"); Put_Line(" requires first > 0, length >= 0"); end Remove_Lines_From_File;
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Keep all operations the same but rewrite the snippet in C.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Convert the following code from AWK to C, ensuring the logic remains intact.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Preserve the algorithm and functionality while converting the code from AWK to C#.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Rewrite this program in C# while keeping its functionality equivalent to the AWK version.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Convert this AWK block to C++, preserving its control flow and logic.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Convert this AWK snippet to C++ and keep its semantics consistent.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Preserve the algorithm and functionality while converting the code from AWK to Java.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Port the provided AWK code into Java while preserving the original functionality.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Keep all operations the same but rewrite the snippet in Python.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Rewrite the snippet below in Python so it works the same as the original AWK code.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Write the same code in VB as shown below in AWK.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Port the provided AWK code into VB while preserving the original functionality.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Can you help me rewrite this code in Go instead of AWK, keeping it the same logically?
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Produce a language-to-language conversion: from AWK to Go, same semantics.
BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(errors+0) } function build_test_data( fn,i,j) { for (i=1; i<=3; i++) { fn = "TEST" i for (j=1; j<=10; j++) { printf("line %d\n",j) >fn } close(fn) } } function remove_lines(fn,start,number_of_lines, arr,fnr,i,n,rec,stop) { stop = start + number_of_lines - 1 while (getline rec <fn > 0) { fnr++ if (fnr < start || fnr > stop) { arr[++n] = rec } } close(fn) if (fnr == 0) { printf("error: file %s not found\n",fn) errors = 1 return } for (i=1; i<=n; i++) { printf("%s\n",arr[i]) >fn } close(fn) if (stop > fnr) { printf("error: file %s trying to remove nonexistent lines\n",fn) errors = 1 } }
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Port the provided Clojure code into C while preserving the original functionality.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Ensure the translated C code behaves exactly like the original Clojure snippet.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Convert this Clojure block to C#, preserving its control flow and logic.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Write the same code in C++ as shown below in Clojure.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Can you help me rewrite this code in C++ instead of Clojure, keeping it the same logically?
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Generate an equivalent Java version of this Clojure code.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Please provide an equivalent version of this Clojure code in Java.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Can you help me rewrite this code in Python instead of Clojure, keeping it the same logically?
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Write a version of this Clojure function in Python with identical behavior.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Rewrite this program in VB while keeping its functionality equivalent to the Clojure version.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Produce a language-to-language conversion: from Clojure to VB, same semantics.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Produce a functionally identical Go code for the snippet given in Clojure.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Port the provided Clojure code into Go while preserving the original functionality.
(require '[clojure.java.io :as jio] '[clojure.string :as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Write the same algorithm in C as shown in this Common_Lisp implementation.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Convert this Common_Lisp block to C, preserving its control flow and logic.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Port the following code from Common_Lisp to C# with equivalent syntax and logic.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Port the following code from Common_Lisp to C# with equivalent syntax and logic.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Rewrite this program in C++ while keeping its functionality equivalent to the Common_Lisp version.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Rewrite this program in C++ while keeping its functionality equivalent to the Common_Lisp version.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Generate a Java translation of this Common_Lisp snippet without changing its computational steps.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Convert this Common_Lisp snippet to Java and keep its semantics consistent.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Rewrite the snippet below in Python so it works the same as the original Common_Lisp code.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Change the following Common_Lisp code into Python without altering its purpose.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
import fileinput, sys fname, start, count = sys.argv[1:4] start, count = int(start), int(count) for line in fileinput.input(fname, inplace=1, backup='.orig'): if start <= fileinput.lineno() < start + count: pass else: print line.rstrip("\n") fileinput.close()
Rewrite the snippet below in VB so it works the same as the original Common_Lisp code.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Transform the following Common_Lisp implementation into VB, maintaining the same output and logic.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
Option Explicit Sub Main() RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 End Sub Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) Dim Nb As Integer, s As String, count As Long, out As String Nb = FreeFile Open StrFile For Input As #Nb While Not EOF(Nb) count = count + 1 Line Input #Nb, s If count < StartLine Or count >= StartLine + NumberOfLines Then out = out & s & vbCrLf End If Wend Close #Nb If StartLine >= count Then MsgBox "The file contains only " & count & " lines" ElseIf StartLine + NumberOfLines > count Then MsgBox "You only can remove " & count - StartLine & " lines" Else Nb = FreeFile Open StrFile For Output As #Nb Print #Nb, out Close #Nb End If End Sub
Can you help me rewrite this code in Go instead of Common_Lisp, keeping it the same logically?
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Rewrite this program in Go while keeping its functionality equivalent to the Common_Lisp version.
(defun remove-lines (filename start num) (let ((tmp-filename (concatenate 'string filename ".tmp")) (lines-omitted 0)) (with-open-file (out tmp-filename :direction :output :if-exists :supersede :if-does-not-exist :create) (with-open-file (in filename) (loop for line = (read-line in nil 'eof) for i from 1 until (eql line 'eof) do (if (or (< i start) (>= i (+ start num))) (write-line line out) (setf lines-omitted (1+ lines-omitted)))))) (delete-file filename) (rename-file tmp-filename filename) (when (< lines-omitted num) (warn "End of file reached with only ~d lines removed." lines-omitted))))
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Can you help me rewrite this code in C instead of D, keeping it the same logically?
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Ensure the translated C code behaves exactly like the original D snippet.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg) int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR("Usage: %s <file> <start> <count>", argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR("Error: <start> (%d) must be positive", start); if ((fp = fopen(argv[1], "r")) == NULL) ERROR("No such file: %s", argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR("Error: invalid parameters for file with %d lines", --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], "w", fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
Translate this program into C# but keep the logic exactly as in D.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Keep all operations the same but rewrite the snippet in C#.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
using System; using System.IO; using System.Linq; public class Rosetta { public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2); static void RemoveLines(string filename, int start, int count = 1) => File.WriteAllLines(filename, File.ReadAllLines(filename) .Where((line, index) => index < start - 1 || index >= start + count - 1)); }
Write the same code in C++ as shown below in D.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Rewrite the snippet below in C++ so it works the same as the original D code.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
#include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <list> void deleteLines( const std::string & , int , int ) ; int main( int argc, char * argv[ ] ) { if ( argc != 4 ) { std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ; return 1 ; } std::string filename( argv[ 1 ] ) ; int startfrom = atoi( argv[ 2 ] ) ; int howmany = atoi( argv[ 3 ] ) ; deleteLines ( filename , startfrom , howmany ) ; return 0 ; } void deleteLines( const std::string & filename , int start , int skip ) { std::ifstream infile( filename.c_str( ) , std::ios::in ) ; if ( infile.is_open( ) ) { std::string line ; std::list<std::string> filelines ; while ( infile ) { getline( infile , line ) ; filelines.push_back( line ) ; } infile.close( ) ; if ( start > filelines.size( ) ) { std::cerr << "Error! Starting to delete lines past the end of the file!\n" ; return ; } if ( ( start + skip ) > filelines.size( ) ) { std::cerr << "Error! Trying to delete lines past the end of the file!\n" ; return ; } std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ; for ( int i = 1 ; i < start ; i++ ) deletebegin++ ; deleteend = deletebegin ; for( int i = 0 ; i < skip ; i++ ) deleteend++ ; filelines.erase( deletebegin , deleteend ) ; std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ; if ( outfile.is_open( ) ) { for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ; sli != filelines.end( ) ; sli++ ) outfile << *sli << "\n" ; } outfile.close( ) ; } else { std::cerr << "Error! Could not find file " << filename << " !\n" ; return ; } }
Write a version of this D function in Java with identical behavior.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
Preserve the algorithm and functionality while converting the code from D to Java.
import std.stdio, std.file, std.string; void main() { deleteLines("deleteline_test.txt", 1, 2); } void deleteLines(string name, int start, int num) in { assert(start > 0, "Line counting must start at 1"); } body { start--; if (!exists(name) || !isFile(name)) throw new FileException("File not found"); auto lines = readText(name).splitLines(); if (lines.length < start + num) throw new Exception("Can't delete lines past the end of file!"); auto f = File(name, "w"); foreach (int i, line; lines) { if (start > i || i >= start + num) f.writeln(line); } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class RemoveLines { public static void main(String[] args) { String filename="foobar.txt"; int startline=1; int numlines=2; RemoveLines now=new RemoveLines(); now.delete(filename,startline,numlines); } void delete(String filename, int startline, int numlines) { try { BufferedReader br=new BufferedReader(new FileReader(filename)); StringBuffer sb=new StringBuffer(""); int linenumber=1; String line; while((line=br.readLine())!=null) { if(linenumber<startline||linenumber>=startline+numlines) sb.append(line+"\n"); linenumber++; } if(startline+numlines>linenumber) System.out.println("End of file reached."); br.close(); FileWriter fw=new FileWriter(new File(filename)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }