Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical C code for the snippet given in Pascal. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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;
}
|
Port the provided Pascal code into C while preserving the original functionality. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 a C# translation of this Pascal snippet without changing its computational steps. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 an equivalent C# version of this Pascal code. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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));
}
|
Convert this Pascal block to C++, preserving its control flow and logic. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 Pascal version. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 ;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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());
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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());
}
}
}
|
Change the programming language of this snippet from Pascal to Python without modifying what it does. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 the following code from Pascal to Python, ensuring the logic remains intact. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 Pascal snippet to VB and keep its semantics consistent. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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
|
Convert the following code from Pascal to VB, ensuring the logic remains intact. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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
|
Convert this Pascal snippet to Go and keep its semantics consistent. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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
}
|
Write the same code in Go as shown below in Pascal. | program RemLines;
uses
cthreads,
Classes, SysUtils;
type
TRLResponse=(rlrOk, rlrEmptyFile, rlrNotEnoughLines);
function RemoveLines(const FileName: String; const From, Count: Integer): TRLResponse;
const
LineOffs = Length(LineEnding);
var
TIn, TOut: TFileStream;
tmpFn, MemBuff, FileBuff: String;
EndingPos, CharRead, LineNumber: Integer;
procedure WriteLine(Line: String);
begin
if ((From > 1) and (LineNumber = 1)) or ((From = 1) and (LineNumber = (From+Count))) then
else if ((From = 1) or (From <= LineNumber)) and (LineNumber < (From+Count)) then
Line := ''
else
Line := LineEnding + Line;
if Line <> '' then
TOut.Write(Line[1], Length(Line));
End;
begin
if not FileExists(FileName) then
raise Exception.CreateFmt('No such file %s', [FileName]);
if From < 1 then
raise Exception.Create('First line must be >= 1');
tmpFn := GetTempFileName(ExtractFilePath(FileName), '');
TIn := TFileStream.Create(FileName, fmOpenRead);
try
TOut := TFileStream.Create(tmpFn, fmCreate);
try
FileBuff := StringOfChar(' ', 1024);
LineNumber := 0;
MemBuff := '';
while True do
begin
CharRead := TIn.Read(FileBuff[1], 1024);
if (CharRead = 0) then
break;
MemBuff += Copy(FileBuff, 1, CharRead);
while True do
begin
EndingPos := Pos(LineEnding, MemBuff);
if EndingPos = 0 then
break;
Inc(LineNumber);
WriteLine(Copy(MemBuff, 1, EndingPos - 1));
MemBuff := Copy(MemBuff, EndingPos + LineOffs, MaxInt);
end;
end;
Inc(LineNumber);
WriteLine(MemBuff);
finally
TOut.Free;
end;
finally
TIn.Free;
end;
if DeleteFile(FileName) then
RenameFile(tmpFn, FileName)
else
raise Exception.Create('Unable to process the file');
if (LineNumber = 0) then
Result := rlrEmptyFile
else if (LineNumber < (From+Count-1)) then
Result := rlrNotEnoughLines
else
Result := rlrOk;
End;
var
FileName: String;
begin
FileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'test.txt';
try
case RemoveLines(FileName, 4, 3) of
rlrOk: WriteLn('Lines deleted');
rlrEmptyFile: WriteLn(Format('File "%s" is empty!', [FileName]));
rlrNotEnoughLines: WriteLn('Can''t delete lines past the end of file');
end
except
on E: Exception do
WriteLn('Error: ' + E.Message);
end;
ReadLn;
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 Perl code into C without altering its purpose. |
print unless $. >= $from && $. <= $to;
| #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 Perl code in C. |
print unless $. >= $from && $. <= $to;
| #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 Perl code. |
print unless $. >= $from && $. <= $to;
| 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));
}
|
Transform the following Perl implementation into C#, maintaining the same output and logic. |
print unless $. >= $from && $. <= $to;
| 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));
}
|
Produce a functionally identical C++ code for the snippet given in Perl. |
print unless $. >= $from && $. <= $to;
| #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 ;
}
}
|
Change the programming language of this snippet from Perl to C++ without modifying what it does. |
print unless $. >= $from && $. <= $to;
| #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 ;
}
}
|
Ensure the translated Java code behaves exactly like the original Perl snippet. |
print unless $. >= $from && $. <= $to;
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Port the provided Perl code into Java while preserving the original functionality. |
print unless $. >= $from && $. <= $to;
| 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 Perl snippet to Python and keep its semantics consistent. |
print unless $. >= $from && $. <= $to;
|
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 this program into Python but keep the logic exactly as in Perl. |
print unless $. >= $from && $. <= $to;
|
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()
|
Transform the following Perl implementation into VB, maintaining the same output and logic. |
print unless $. >= $from && $. <= $to;
| 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
|
Change the programming language of this snippet from Perl to VB without modifying what it does. |
print unless $. >= $from && $. <= $to;
| 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
|
Convert the following code from Perl to Go, ensuring the logic remains intact. |
print unless $. >= $from && $. <= $to;
| 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 Perl version. |
print unless $. >= $from && $. <= $to;
| 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 PowerShell to C, ensuring the logic remains intact. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| #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 a C translation of this PowerShell snippet without changing its computational steps. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| #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 a C# translation of this PowerShell snippet without changing its computational steps. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Rewrite this program in C# while keeping its functionality equivalent to the PowerShell version. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| 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));
}
|
Transform the following PowerShell implementation into C++, maintaining the same output and logic. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| #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 ;
}
}
|
Ensure the translated C++ code behaves exactly like the original PowerShell snippet. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| #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 ;
}
}
|
Change the programming language of this snippet from PowerShell to Java without modifying what it does. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| 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 PowerShell to Python, ensuring the logic remains intact. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Rewrite the snippet below in Python so it works the same as the original PowerShell code. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
|
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 PowerShell code into VB without altering its purpose. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| 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
|
Maintain the same structure and functionality when rewriting this code in VB. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| 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
|
Please provide an equivalent version of this PowerShell code in Go. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| 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 Go but keep the logic exactly as in PowerShell. | function del-line($file, $start, $end) {
$i = 0
$start--
$end--
(Get-Content $file) | where{
($i -lt $start -or $i -gt $end)
$i++
} > $file
(Get-Content $file)
}
del-line "foobar.txt" 1 2
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Write the same code in C as shown below in Racket. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Convert this Racket block to C, preserving its control flow and logic. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| #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 provided Racket code into C# while preserving the original functionality. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Port the provided Racket code into C# while preserving the original functionality. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Convert this Racket block to C++, preserving its control flow and logic. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Can you help me rewrite this code in C++ instead of Racket, keeping it the same logically? | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| #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 the given Racket code snippet into Java without altering its behavior. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| 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());
}
}
}
|
Write a version of this Racket function in Java with identical behavior. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| 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 Racket to Python, ensuring the logic remains intact. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
|
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 this program into Python but keep the logic exactly as in Racket. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
|
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 Racket code into VB while preserving the original functionality. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| 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
|
Convert this Racket block to VB, preserving its control flow and logic. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| 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 Go so it works the same as the original Racket code. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Produce a language-to-language conversion: from Racket to Go, same semantics. | #lang racket
(define (remove-lines file from num)
(define lines (file->lines file))
(define-values [pfx rest] (split-at lines (sub1 from)))
(display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))
| 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. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Write a version of this REXX function in C with identical behavior. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original REXX snippet. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Rewrite this program in C# while keeping its functionality equivalent to the REXX version. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Please provide an equivalent version of this REXX code in C++. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Change the programming language of this snippet from REXX to C++ without modifying what it does. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Change the following REXX code into Java without altering its purpose. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Translate this program into Java but keep the logic exactly as in REXX. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Port the following code from REXX to Python with equivalent syntax and logic. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Rewrite the snippet below in Python so it works the same as the original REXX code. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Transform the following REXX implementation into VB, maintaining the same output and logic. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Translate the given REXX code snippet into VB without altering its behavior. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Write the same algorithm in Go as shown in this REXX implementation. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Change the programming language of this snippet from REXX to Go without modifying what it does. |
parse arg iFID ',' N "," many .
if iFID='' then call er "no input fileID specified."
if N='' then call er "no start number specified."
if many='' then many=1
stop=N+many-1
oFID=iFID'.$$$'
#=0
do j=1 while lines(iFID)\==0
@=linein(iFID)
if j>=N & j<=stop then iterate
call lineout oFID,@; #=#+1
end
j=j-1
if j<stop then say "The number of lines in file is less than the range given."
$='"'
'ERASE' $ || iFID || $
'RENAME' $ || oFID || $ $ || iFID || $
say 'file ' iFID " had" j 'record's(j)", it now has" # 'record's(w)"."
exit
er: say; say '***error***'; say; say arg(1); say; exit 13
s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Produce a functionally identical C code for the snippet given in Ruby. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Ruby version. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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 Ruby code. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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));
}
|
Convert this Ruby snippet to C# and keep its semantics consistent. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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));
}
|
Port the following code from Ruby to C++ with equivalent syntax and logic. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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 the same code in C++ as shown below in Ruby. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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 Java while keeping its functionality equivalent to the Ruby version. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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());
}
}
}
|
Change the following Ruby code into Python without altering its purpose. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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 Ruby block to Python, preserving its control flow and logic. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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()
|
Preserve the algorithm and functionality while converting the code from Ruby to VB. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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
|
Generate a VB translation of this Ruby snippet without changing its computational steps. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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
|
Generate a Go translation of this Ruby snippet without changing its computational steps. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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
}
|
Convert the following code from Ruby to Go, ensuring the logic remains intact. | require 'tempfile'
def remove_lines(filename, start, num)
tmp = Tempfile.open(filename) do |fp|
File.foreach(filename) do |line|
if $. >= start and num > 0
num -= 1
else
fp.puts line
end
end
fp
end
puts "Warning: End of file encountered before all lines removed" if num > 0
FileUtils.copy(tmp.path, filename)
tmp.unlink
end
def setup(filename, start, remove)
puts "remove
File.open(filename, "w") {|fh| (1..5).each {|i| fh.puts " "*i + i.to_s}}
puts "before:", File.read(filename)
end
def teardown(filename)
puts "after:", File.read(filename)
puts
File.unlink(filename)
end
filename = "foobar.txt"
start = 2
[2, 6].each do |remove|
setup(filename, start, remove)
remove_lines(filename, start, remove)
teardown(filename)
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
}
|
Write the same algorithm in C as shown in this Scala implementation. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| #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;
}
|
Write the same algorithm in C as shown in this Scala implementation. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| #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;
}
|
Write a version of this Scala function in C# with identical behavior. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Port the provided Scala code into C# while preserving the original functionality. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Rewrite the snippet below in C++ so it works the same as the original Scala code. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| #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 ;
}
}
|
Ensure the translated C++ code behaves exactly like the original Scala snippet. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| #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 ;
}
}
|
Produce a language-to-language conversion: from Scala to Java, same semantics. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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());
}
}
}
|
Write the same algorithm in Java as shown in this Scala implementation. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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 an equivalent Python version of this Scala code. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
|
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 Scala to Python without modifying what it does. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
|
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()
|
Generate a VB translation of this Scala snippet without changing its computational steps. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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 Scala. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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 Scala snippet. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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 the given Scala code snippet into Go without altering its behavior. |
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
}
| 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 Tcl to C. | proc removeLines {fileName startLine count} {
set from [expr {$startLine - 1}]
set to [expr {$startLine + $count - 2}]
set f [open $fileName]
set lines [split [read $f] "\n"]
close $f
set f [open $fileName w]
puts -nonewline $f [join [lreplace $lines $from $to] "\n"]
close $f
}
| #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 provided Tcl code into C while preserving the original functionality. | proc removeLines {fileName startLine count} {
set from [expr {$startLine - 1}]
set to [expr {$startLine + $count - 2}]
set f [open $fileName]
set lines [split [read $f] "\n"]
close $f
set f [open $fileName w]
puts -nonewline $f [join [lreplace $lines $from $to] "\n"]
close $f
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Convert the following code from Tcl to C#, ensuring the logic remains intact. | proc removeLines {fileName startLine count} {
set from [expr {$startLine - 1}]
set to [expr {$startLine + $count - 2}]
set f [open $fileName]
set lines [split [read $f] "\n"]
close $f
set f [open $fileName w]
puts -nonewline $f [join [lreplace $lines $from $to] "\n"]
close $f
}
| 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));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.