Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in Python as shown in this D implementation. | 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 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()
|
Produce a language-to-language conversion: from D to Python, same semantics. | 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 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 this D snippet to VB and keep its semantics consistent. | 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);
}
}
| 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
|
Write a version of this D function in VB 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);
}
}
| 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 Go translation of this D snippet without changing its computational steps. | 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);
}
}
| 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 a version of this D function in Go 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);
}
}
| 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
}
|
Please provide an equivalent version of this Delphi code in C. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| #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 Delphi to C. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| #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;
}
|
Generate an equivalent C# version of this Delphi code. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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));
}
|
Generate a C# translation of this Delphi snippet without changing its computational steps. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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));
}
|
Maintain the same structure and functionality when rewriting this code in C++. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| #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 C++ version of this Delphi code. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| #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 Delphi function in Java with identical behavior. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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 the following code from Delphi to Java, ensuring the logic remains intact. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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 Delphi code. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
|
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()
|
Produce a functionally identical Python code for the snippet given in Delphi. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
|
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 Delphi code into VB without altering its purpose. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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
|
Write the same code in VB as shown below in Delphi. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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 Delphi code into Go while preserving the original functionality. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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
}
|
Change the following Delphi code into Go without altering its purpose. | program Remove_lines_from_a_file_using_TStringDynArray;
uses
System.SysUtils,
System.IoUtils;
procedure RemoveLines(FileName: TFileName; Index, Line_count: Cardinal);
begin
if not FileExists(FileName) then
exit;
var lines := TFile.ReadAllLines(FileName);
Delete(lines, Index, Line_count);
TFile.WriteAllLines(FileName, lines);
end;
begin
RemoveLines('input.txt', 1, 2);
end.
| 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
}
|
Keep all operations the same but rewrite the snippet in C. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| #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;
}
|
Change the following Elixir code into C without altering its purpose. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| #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;
}
|
Please provide an equivalent version of this Elixir code in C#. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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));
}
|
Generate an equivalent C# version of this Elixir code. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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));
}
|
Change the following Elixir code into C++ without altering its purpose. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| #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 C++ version of this Elixir code. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| #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 ;
}
}
|
Translate this program into Java but keep the logic exactly as in Elixir. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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());
}
}
}
|
Ensure the translated Java code behaves exactly like the original Elixir snippet. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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());
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
|
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 programming language of this snippet from Elixir to Python without modifying what it does. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
|
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 Elixir code into VB without altering its purpose. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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
|
Translate the given Elixir code snippet into VB without altering its behavior. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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 Elixir implementation into Go, maintaining the same output and logic. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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
}
|
Convert the following code from Elixir to Go, ensuring the logic remains intact. | defmodule RC do
def remove_lines(filename, start, number) do
File.open!(filename, [:read], fn file ->
remove_lines(file, start, number, IO.read(file, :line))
end)
end
defp remove_lines(_file, 0, 0, :eof), do: :ok
defp remove_lines(_file, _, _, :eof) do
IO.puts(:stderr, "Warning: End of file encountered before all lines removed")
end
defp remove_lines(file, 0, 0, line) do
IO.write line
remove_lines(file, 0, 0, IO.read(file, :line))
end
defp remove_lines(file, 0, number, _line) do
remove_lines(file, 0, number-1, IO.read(file, :line))
end
defp remove_lines(file, start, number, line) do
IO.write line
remove_lines(file, start-1, number, IO.read(file, :line))
end
end
[filename, start, number] = System.argv
IO.puts "before:"
IO.puts File.read!(filename)
IO.puts "after:"
RC.remove_lines(filename, String.to_integer(start), String.to_integer(number)
| 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 a version of this Erlang function in C with identical behavior. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| #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 Erlang to C with equivalent syntax and logic. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| #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;
}
|
Rewrite the snippet below in C# so it works the same as the original Erlang code. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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));
}
|
Can you help me rewrite this code in C# instead of Erlang, keeping it the same logically? | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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));
}
|
Change the programming language of this snippet from Erlang to C++ without modifying what it does. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| #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 ;
}
}
|
Keep all operations the same but rewrite the snippet in C++. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| #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 Erlang block to Java, preserving its control flow and logic. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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());
}
}
}
|
Generate a Java translation of this Erlang snippet without changing its computational steps. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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());
}
}
}
|
Ensure the translated Python code behaves exactly like the original Erlang snippet. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
|
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()
|
Please provide an equivalent version of this Erlang code in Python. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
|
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 Erlang. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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 following code from Erlang to VB with equivalent syntax and logic. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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
|
Ensure the translated Go code behaves exactly like the original Erlang snippet. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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
}
|
Convert the following code from Erlang to Go, ensuring the logic remains intact. | -module( remove_lines ).
-export( [from_file/3, task/0] ).
from_file( Name, Start, How_many ) ->
{Name, {ok, Binary}} = {Name, file:read_file( Name )},
Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ),
io:fwrite( "~s~n", [Message] ).
task() ->
file:copy( "priv/foobar.txt", "foobar.txt" ),
from_file( "foobar.txt", 1, 2 ).
compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).
keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many > Available ->
Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
{Keeps, _Removes} = lists:split( Start, Lines ),
{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
{Keeps, Removes} = lists:split( Start, Lines ),
{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.
| 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
}
|
Preserve the algorithm and functionality while converting the code from F# to C. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| #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;
}
|
Please provide an equivalent version of this F# code in C. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| #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 F#. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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));
}
|
Can you help me rewrite this code in C# instead of F#, keeping it the same logically? | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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 algorithm in C++ as shown in this F# implementation. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| #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 ;
}
}
|
Keep all operations the same but rewrite the snippet in C++. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| #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 F# snippet without changing its computational steps. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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());
}
}
}
|
Translate the given F# code snippet into Java without altering its behavior. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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());
}
}
}
|
Generate a Python translation of this F# snippet without changing its computational steps. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
|
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 Python while keeping its functionality equivalent to the F# version. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
|
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 algorithm in VB as shown in this F# implementation. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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
|
Rewrite the snippet below in VB so it works the same as the original F# code. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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 an equivalent Go version of this F# code. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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 F# version. | open System
open System.IO
let cutOut (arr : 'a[]) from n =
let slicer = fun i -> if i < from || (from + n) <= i then Some(arr.[i-1]) else None
((Array.choose slicer [| 1 .. arr.Length |]), from + n - arr.Length > 1)
[<EntryPoint>]
let main argv =
let nums = Array.choose (System.Int32.TryParse >> function | true, v -> Some v | false, _ -> None) argv.[1..2]
let lines = File.ReadAllLines(argv.[0])
let (sliced, tooShort) = cutOut lines nums.[0] nums.[1]
if tooShort then Console.Error.WriteLine "Not enough lines"
File.WriteAllLines(argv.[0], sliced)
0
| 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
}
|
Change the programming language of this snippet from Fortran to C# without modifying what it does. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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 a version of this Fortran function in C# with identical behavior. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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));
}
|
Preserve the algorithm and functionality while converting the code from Fortran to C++. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| #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 Fortran code. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| #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 Fortran version. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| #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;
}
|
Keep all operations the same but rewrite the snippet in C. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| #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 Go code behaves exactly like the original Fortran snippet. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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
}
|
Translate this program into Java but keep the logic exactly as in Fortran. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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());
}
}
}
|
Transform the following Fortran implementation into Java, maintaining the same output and logic. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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 Fortran snippet to Python and keep its semantics consistent. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
|
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 Python while keeping its functionality equivalent to the Fortran version. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
|
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 this Fortran snippet to VB and keep its semantics consistent. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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
|
Write a version of this Fortran function in VB with identical behavior. | SUBROUTINE CROAK(GASP)
CHARACTER*(*) GASP
WRITE (6,*) "Oh dear. ",GASP
STOP "++ungood."
END
SUBROUTINE FILEHACK(FNAME,IST,N)
CHARACTER*(*) FNAME
INTEGER IST
INTEGER N
INTEGER ENUFF,L
PARAMETER (ENUFF = 66666)
CHARACTER*(ENUFF) ALINE
INTEGER NREC
INTEGER F,T
PARAMETER (F=66,T=67)
LOGICAL EXIST
IF (FNAME.EQ."") CALL CROAK("Blank file name
IF (IST.LE.0) CALL CROAK("First record must be positive
IF (N.LE.0) CALL CROAK("Remove count must be positive
INQUIRE(FILE = FNAME, EXIST = EXIST)
IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)
OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED")
OPEN (T,STATUS="SCRATCH",FORM="FORMATTED")
NREC = 0
Copy the desired records to a temporary file.
10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF))
11 FORMAT (Q,A)
IF (L.GT.ENUFF) CALL CROAK("Ow
NREC = NREC + 1
IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L)
12 FORMAT (A)
GO TO 10
Convert from input to output...
20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records
REWIND T
CLOSE(F)
OPEN (F,FILE=FNAME,FORM="FORMATTED",
1 ACTION="WRITE",STATUS="REPLACE")
Copy from the temporary file.
21 READ (T,11,END = 30) L,ALINE(1:L)
WRITE (F,12) ALINE(1:L)
GO TO 21
Completed.
30 CLOSE(T)
CLOSE(F)
END
PROGRAM CHOPPER
CALL FILEHACK("foobar.txt",1,2)
END
| 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
|
Rewrite this program in C while keeping its functionality equivalent to the Groovy version. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| #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 Groovy. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| #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;
}
|
Change the following Groovy code into C# without altering its purpose. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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));
}
|
Preserve the algorithm and functionality while converting the code from Groovy to C#. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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));
}
|
Ensure the translated C++ code behaves exactly like the original Groovy snippet. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| #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 ;
}
}
|
Transform the following Groovy implementation into C++, maintaining the same output and logic. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| #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 ;
}
}
|
Translate this program into Java but keep the logic exactly as in Groovy. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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 Java so it works the same as the original Groovy code. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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());
}
}
}
|
Produce a functionally identical Python code for the snippet given in Groovy. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
|
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()
|
Produce a functionally identical Python code for the snippet given in Groovy. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
|
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()
|
Port the provided Groovy code into VB while preserving the original functionality. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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 Groovy to VB, same semantics. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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 Groovy implementation into Go, maintaining the same output and logic. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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
}
|
Convert this Groovy block to Go, preserving its control flow and logic. | static def removeLines(String filename, int startingLine, int lineCount) {
def sourceFile = new File(filename).getAbsoluteFile()
def outputFile = File.createTempFile("remove", ".tmp", sourceFile.getParentFile())
outputFile.withPrintWriter { outputWriter ->
sourceFile.eachLine { line, lineNumber ->
if (lineNumber < startingLine || lineNumber - startingLine >= lineCount)
outputWriter.println(line)
}
}
outputFile.renameTo(sourceFile)
}
removeLines(args[0], args[1] as Integer, args[2] as Integer)
| 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
}
|
Generate a C translation of this Haskell snippet without changing its computational steps. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| #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;
}
|
Please provide an equivalent version of this Haskell code in C. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| #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;
}
|
Can you help me rewrite this code in C# instead of Haskell, keeping it the same logically? | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| 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));
}
|
Change the following Haskell code into C# without altering its purpose. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| 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));
}
|
Generate an equivalent C++ version of this Haskell code. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| #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 Haskell code. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| #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 ;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| 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 Haskell to Java. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| 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 the following code from Haskell to Python, ensuring the logic remains intact. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
|
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()
|
Translate the given Haskell code snippet into Python without altering its behavior. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
|
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 this Haskell snippet to VB and keep its semantics consistent. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.