Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Read-a-specific-line-from-a-file/00-META.yaml
Normal file
2
Task/Read-a-specific-line-from-a-file/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
|
||||
17
Task/Read-a-specific-line-from-a-file/00-TASK.txt
Normal file
17
Task/Read-a-specific-line-from-a-file/00-TASK.txt
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
Some languages have special semantics for obtaining a known line number from a file.
|
||||
|
||||
|
||||
;Task:
|
||||
Demonstrate how to obtain the contents of a specific line within a file.
|
||||
|
||||
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
|
||||
|
||||
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
|
||||
|
||||
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
|
||||
|
||||
Note that empty lines are considered and should still be counted.
|
||||
|
||||
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
V f = File(‘input.txt’)
|
||||
V line = 3
|
||||
|
||||
L 0 .< line - 1
|
||||
f.read_line()
|
||||
print(f.read_line())
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
# reads the line with number "number" (counting from 1) #
|
||||
# from the file named "file name" and returns the text of the #
|
||||
# in "line". If an error occurs, the result is FALSE and a #
|
||||
# message is returned in "err". If no error occurs, TRUE is #
|
||||
# returned #
|
||||
PROC read specific line = ( STRING file name
|
||||
, INT number # line 7 #
|
||||
, REF STRING line
|
||||
, REF STRING err
|
||||
)BOOL:
|
||||
IF FILE input file;
|
||||
line := "";
|
||||
open( input file, file name, stand in channel ) /= 0
|
||||
THEN
|
||||
# failed to open the file #
|
||||
err := "Unable to open """ + file name + """";
|
||||
FALSE
|
||||
ELSE
|
||||
# file opened OK #
|
||||
err := "";
|
||||
BOOL at eof := FALSE;
|
||||
# set the EOF handler for the file #
|
||||
on logical file end( input file
|
||||
, ( REF FILE f )BOOL:
|
||||
BEGIN
|
||||
# note that we reached EOF on the #
|
||||
# latest read #
|
||||
at eof := TRUE;
|
||||
|
||||
# return TRUE so processing can continue #
|
||||
TRUE
|
||||
END
|
||||
);
|
||||
INT line number := 0;
|
||||
STRING text;
|
||||
WHILE line number < number
|
||||
AND NOT at eof
|
||||
DO
|
||||
get( input file, ( text, newline ) );
|
||||
line number +:= 1
|
||||
OD;
|
||||
# close the file #
|
||||
close( input file );
|
||||
# return the line or an error message depending on whether #
|
||||
# we got a line with the required number or not #
|
||||
IF line number = number
|
||||
THEN
|
||||
# got the required line #
|
||||
line := text;
|
||||
TRUE
|
||||
ELSE
|
||||
# not enough lines in the file #
|
||||
err := """" + file name + """ is too short";
|
||||
FALSE
|
||||
FI
|
||||
FI; # read specific line #
|
||||
main:(
|
||||
# read the seventh line of this source and print it #
|
||||
# (or an error message if we can't) #
|
||||
STRING line;
|
||||
STRING err;
|
||||
IF read specific line( "read-specific-line.a68", 7, line, err )
|
||||
THEN
|
||||
# got the line #
|
||||
print( ( "line seven is: """ + line + """", newline ) )
|
||||
ELSE
|
||||
# got an error #
|
||||
print( ( "unable to read line: """ + err + """" ) )
|
||||
FI
|
||||
)
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
#!/usr/bin/awk -f
|
||||
#usage: readnthline.awk -v lineno=6 filename
|
||||
|
||||
FNR==lineno { storedline=$0; found++ }
|
||||
|
||||
END {
|
||||
if (found < 1) {
|
||||
print "ERROR: Line", lineno, "not found"
|
||||
exit 1
|
||||
}
|
||||
print storedline
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
|
||||
CHAR ARRAY line(255)
|
||||
CARD curr
|
||||
BYTE status,dev=[1]
|
||||
|
||||
Close(dev)
|
||||
Open(dev,fname,4)
|
||||
curr=1 status=1
|
||||
WHILE Eof(dev)=0
|
||||
DO
|
||||
InputSD(dev,line)
|
||||
IF curr=index THEN
|
||||
SCopy(result,line)
|
||||
status=0
|
||||
EXIT
|
||||
FI
|
||||
curr==+1
|
||||
OD
|
||||
Close(dev)
|
||||
RETURN (status)
|
||||
|
||||
PROC Test(CHAR ARRAY fname CARD index)
|
||||
CHAR ARRAY result(255)
|
||||
BYTE status
|
||||
|
||||
PrintF("Reading %U line...%E",index)
|
||||
status=ReadLine(fname,index,result)
|
||||
IF status=0 THEN
|
||||
IF result(0)=0 THEN
|
||||
PrintF("%U line is empty.%E%E",index)
|
||||
ELSE
|
||||
PrintF("%U line is:%E""%S""%E%E",index,result)
|
||||
FI
|
||||
ELSEIF status=1 THEN
|
||||
PrintF("File contains less than %U lines.%E%E",index)
|
||||
FI
|
||||
RETURN
|
||||
|
||||
PROC Main()
|
||||
CHAR ARRAY fname="H6:READ__96.ACT"
|
||||
|
||||
PrintF("Reading ""%S""...%E%E",fname)
|
||||
Test(fname,7)
|
||||
Test(fname,24)
|
||||
Test(fname,50)
|
||||
RETURN
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
|
||||
procedure Rosetta_Read is
|
||||
File : File_Type;
|
||||
begin
|
||||
Open (File => File,
|
||||
Mode => In_File,
|
||||
Name => "rosetta_read.adb");
|
||||
Set_Line (File, To => 7);
|
||||
|
||||
declare
|
||||
Line_7 : constant String := Get_Line (File);
|
||||
begin
|
||||
if Line_7'Length = 0 then
|
||||
Put_Line ("Line 7 is empty.");
|
||||
else
|
||||
Put_Line (Line_7);
|
||||
end if;
|
||||
end;
|
||||
|
||||
Close (File);
|
||||
exception
|
||||
when End_Error =>
|
||||
Put_Line ("The file contains fewer than 7 lines.");
|
||||
Close (File);
|
||||
when Storage_Error =>
|
||||
Put_Line ("Line 7 is too long to load.");
|
||||
Close (File);
|
||||
end Rosetta_Read;
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
void
|
||||
read_line(text &line, text path, integer n)
|
||||
{
|
||||
file f;
|
||||
|
||||
f.affix(path);
|
||||
|
||||
call_n(n, f_slip, f);
|
||||
|
||||
f.line(line);
|
||||
}
|
||||
|
||||
|
||||
integer
|
||||
main(void)
|
||||
{
|
||||
if (1 < argc()) {
|
||||
text line;
|
||||
|
||||
read_line(line, argv(1), 6);
|
||||
|
||||
o_("7th line is:\n", line, "\n");
|
||||
}
|
||||
|
||||
0;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
#include <hopper.h>
|
||||
#define MAX_LINE_SIZE 1000
|
||||
main:
|
||||
v=0, fd=0
|
||||
fsearch("-r $'\n'","archivo.txt")(v)
|
||||
fopen(OPEN_READ,"archivo.txt")(fd)
|
||||
{"Line #7 = "}, fgetsline(fd,MAX_LINE_SIZE,7,v), println
|
||||
try
|
||||
fgetsline(fd,MAX_LINE_SIZE,10,v),
|
||||
catch(e)
|
||||
{"Error search line (code=",e,"): "},get str error
|
||||
finish
|
||||
println
|
||||
fclose(fd)
|
||||
exit(0)
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
lineToRead: 3
|
||||
|
||||
lineRead: get read.lines "myfile.txt" lineToRead
|
||||
|
||||
print lineRead
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
FileReadLine, OutputVar, filename.txt, 7
|
||||
if ErrorLevel
|
||||
MsgBox, There was an error reading the 7th line of the file
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
f = freefile
|
||||
filename$ = "input.txt"
|
||||
open f, filename$
|
||||
|
||||
lineapedida = 7
|
||||
cont = 0
|
||||
while not (eof(f))
|
||||
linea$ = readline(f)
|
||||
cont += 1
|
||||
if cont = lineapedida then
|
||||
if trim(linea$) = "" then print "The 7th line is empty" else print linea$
|
||||
exit while
|
||||
end if
|
||||
end while
|
||||
if cont < lineapedida then print "There are only "; cont; " lines in the file"
|
||||
close f
|
||||
end
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
filepath$ = @lib$ + "..\licence.txt"
|
||||
requiredline% = 7
|
||||
|
||||
file% = OPENIN(filepath$)
|
||||
IF file%=0 ERROR 100, "File could not be opened"
|
||||
FOR i% = 1 TO requiredline%
|
||||
IF EOF#file% ERROR 100, "File contains too few lines"
|
||||
INPUT #file%, text$
|
||||
NEXT
|
||||
CLOSE #file%
|
||||
|
||||
IF ASCtext$=10 text$ = MID$(text$,2)
|
||||
PRINT text$
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
@echo off
|
||||
|
||||
for /f "skip=6 tokens=*" %%i in (file.txt) do (
|
||||
set line7=%%i
|
||||
goto break
|
||||
)
|
||||
:break
|
||||
echo Line 7 is: %line7%
|
||||
pause>nul
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
#include <string>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
int main( ) {
|
||||
std::cout << "Which file do you want to look at ?\n" ;
|
||||
std::string input ;
|
||||
std::getline( std::cin , input ) ;
|
||||
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
|
||||
std::string file( input ) ;
|
||||
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
|
||||
std::getline( std::cin , input ) ;
|
||||
int linenumber = std::stoi( input ) ;
|
||||
int lines_read = 0 ;
|
||||
std::string line ;
|
||||
if ( infile.is_open( ) ) {
|
||||
while ( infile ) {
|
||||
getline( infile , line ) ;
|
||||
lines_read++ ;
|
||||
if ( lines_read == linenumber ) {
|
||||
std::cout << line << std::endl ;
|
||||
break ;
|
||||
}
|
||||
}
|
||||
infile.close( ) ;
|
||||
if ( lines_read < linenumber )
|
||||
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
|
||||
return 0 ;
|
||||
}
|
||||
else {
|
||||
std::cerr << "Could not find file " << file << " !\n" ;
|
||||
return 1 ;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GetLine
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
|
||||
}
|
||||
|
||||
private static string GetLine(string path, uint line)
|
||||
{
|
||||
using (var reader = new StreamReader(path))
|
||||
{
|
||||
try
|
||||
{
|
||||
for (uint i = 0; i <= line; i++)
|
||||
{
|
||||
if (reader.EndOfStream)
|
||||
return string.Format("There {1} less than {0} line{2} in the file.", line,
|
||||
((line == 1) ? "is" : "are"), ((line == 1) ? "" : "s"));
|
||||
|
||||
if (i == line)
|
||||
return reader.ReadLine();
|
||||
|
||||
reader.ReadLine();
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
catch (OutOfMemoryException ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("Something bad happened.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <err.h>
|
||||
|
||||
/* following code assumes all file operations succeed. In practice,
|
||||
* return codes from open, close, fstat, mmap, munmap all need to be
|
||||
* checked for error.
|
||||
*/
|
||||
int read_file_line(const char *path, int line_no)
|
||||
{
|
||||
struct stat s;
|
||||
char *buf;
|
||||
off_t start = -1, end = -1;
|
||||
size_t i;
|
||||
int ln, fd, ret = 1;
|
||||
|
||||
if (line_no == 1) start = 0;
|
||||
else if (line_no < 1){
|
||||
warn("line_no too small");
|
||||
return 0; /* line_no starts at 1; less is error */
|
||||
}
|
||||
|
||||
line_no--; /* back to zero based, easier */
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
fstat(fd, &s);
|
||||
|
||||
/* Map the whole file. If the file is huge (up to GBs), OS will swap
|
||||
* pages in and out, and because search for lines goes sequentially
|
||||
* and never accesses more than one page at a time, penalty is low.
|
||||
* If the file is HUGE, such that OS can't find an address space to map
|
||||
* it, we got a real problem. In practice one would repeatedly map small
|
||||
* chunks, say 1MB at a time, and find the offsets of the line along the
|
||||
* way. Although, if file is really so huge, the line itself can't be
|
||||
* guaranteed small enough to be "stored in memory", so there.
|
||||
*/
|
||||
buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
|
||||
/* optional; if the file is large, tell OS to read ahead */
|
||||
madvise(buf, s.st_size, MADV_SEQUENTIAL);
|
||||
|
||||
for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
|
||||
if (buf[i] != '\n') continue;
|
||||
|
||||
if (++ln == line_no) start = i + 1;
|
||||
else if (ln == line_no + 1) end = i + 1;
|
||||
}
|
||||
|
||||
if (start >= s.st_size || start < 0) {
|
||||
warn("file does not have line %d", line_no + 1);
|
||||
ret = 0;
|
||||
} else {
|
||||
/* do something with the line here, like
|
||||
write(STDOUT_FILENO, buf + start, end - start);
|
||||
or copy it out, or something
|
||||
*/
|
||||
}
|
||||
|
||||
munmap(buf, s.st_size);
|
||||
close(fd);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define BUF_SIZE ( 256 )
|
||||
|
||||
char *get_nth_line( FILE *f, int line_no )
|
||||
{
|
||||
char buf[ BUF_SIZE ];
|
||||
size_t curr_alloc = BUF_SIZE, curr_ofs = 0;
|
||||
char *line = malloc( BUF_SIZE );
|
||||
int in_line = line_no == 1;
|
||||
size_t bytes_read;
|
||||
|
||||
/* Illegal to ask for a line before the first one. */
|
||||
if ( line_no < 1 )
|
||||
return NULL;
|
||||
|
||||
/* Handle out-of-memory by returning NULL */
|
||||
if ( !line )
|
||||
return NULL;
|
||||
|
||||
/* Scan the file looking for newlines */
|
||||
while ( line_no &&
|
||||
( bytes_read = fread( buf, 1, BUF_SIZE, f ) ) > 0 )
|
||||
{
|
||||
int i;
|
||||
|
||||
for ( i = 0 ; i < bytes_read ; i++ )
|
||||
{
|
||||
if ( in_line )
|
||||
{
|
||||
if ( curr_ofs >= curr_alloc )
|
||||
{
|
||||
curr_alloc <<= 1;
|
||||
line = realloc( line, curr_alloc );
|
||||
|
||||
if ( !line ) /* out of memory? */
|
||||
return NULL;
|
||||
}
|
||||
line[ curr_ofs++ ] = buf[i];
|
||||
}
|
||||
|
||||
if ( buf[i] == '\n' )
|
||||
{
|
||||
line_no--;
|
||||
|
||||
if ( line_no == 1 )
|
||||
in_line = 1;
|
||||
|
||||
if ( line_no == 0 )
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Didn't find the line? */
|
||||
if ( line_no != 0 )
|
||||
{
|
||||
free( line );
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Resize allocated buffer to what's exactly needed by the string
|
||||
and the terminating NUL character. Note that this code *keeps*
|
||||
the terminating newline as part of the string.
|
||||
*/
|
||||
line = realloc( line, curr_ofs + 1 );
|
||||
|
||||
if ( !line ) /* out of memory? */
|
||||
return NULL;
|
||||
|
||||
/* Add the terminating NUL. */
|
||||
line[ curr_ofs ] = '\0';
|
||||
|
||||
/* Return the line. Caller is responsible for freeing it. */
|
||||
return line;
|
||||
}
|
||||
|
||||
|
||||
/* Test program. Prints out the 7th line of input from stdin, if any */
|
||||
int main( int argc, char *argv[] )
|
||||
{
|
||||
char *line7 = get_nth_line( stdin, 7 );
|
||||
|
||||
if ( line7 )
|
||||
{
|
||||
printf("The 7th line of input was:\n%s\n", line7 );
|
||||
free( line7 );
|
||||
} else
|
||||
{
|
||||
printf("Did not find the 7th line of input. Reason: ");
|
||||
if ( feof( stdin ) )
|
||||
puts("End of file reached.");
|
||||
else if ( ferror( stdin ) )
|
||||
puts("Error reading input.");
|
||||
else
|
||||
puts("Out of memory.");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
(defn read-nth-line
|
||||
"Read line-number from the given text file. The first line has the number 1."
|
||||
[file line-number]
|
||||
(with-open [rdr (clojure.java.io/reader file)]
|
||||
(nth (line-seq rdr) (dec line-number))))
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
(defun read-nth-line (file n &aux (line-number 0))
|
||||
"Read the nth line from a text file. The first line has the number 1"
|
||||
(assert (> n 0) (n))
|
||||
(with-open-file (stream file)
|
||||
(loop for line = (read-line stream nil nil)
|
||||
if (and (null line) (< line-number n))
|
||||
do (error "file ~a is too short, just ~a, not ~a lines long"
|
||||
file line-number n)
|
||||
do (incf line-number)
|
||||
if (and line (= line-number n))
|
||||
do (return line))))
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
void main() {
|
||||
import std.stdio, std.file, std.string;
|
||||
auto file_lines = readText("input.txt").splitLines();
|
||||
//file_lines becomes an array of strings, each line is one element
|
||||
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import std.stdio;
|
||||
|
||||
void main() {
|
||||
int countLines;
|
||||
char[] ln;
|
||||
auto f = File("linenumber.d", "r");
|
||||
foreach (char[] line; f.byLine()) {
|
||||
countLines++;
|
||||
if (countLines == 7) {
|
||||
ln = line;
|
||||
break;
|
||||
}
|
||||
}
|
||||
switch(countLines) {
|
||||
case 0 : writeln("the file has zero length");
|
||||
break;
|
||||
case 7 : writeln("line 7: ", (ln.length ? ln : "empty"));
|
||||
break;
|
||||
default :
|
||||
writefln("the file only contains %d lines", countLines);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
program Read_a_specific_line_from_a_file;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses
|
||||
System.SysUtils;
|
||||
|
||||
function ReadLine(position: Cardinal; FileName: TFileName): string;
|
||||
begin
|
||||
Result := '';
|
||||
|
||||
if not FileExists(FileName) then
|
||||
raise Exception.Create('Error: File does not exist.');
|
||||
|
||||
var F: TextFile;
|
||||
var line: string;
|
||||
AssignFile(F, FileName);
|
||||
Reset(F);
|
||||
for var _ := 1 to position do
|
||||
begin
|
||||
if Eof(F) then
|
||||
begin
|
||||
CloseFile(F);
|
||||
|
||||
raise Exception.Create(Format('Error: The file "%s" is too short. Cannot read line %d',
|
||||
[FileName, position]));
|
||||
end;
|
||||
|
||||
Readln(F, line);
|
||||
end;
|
||||
CloseFile(F);
|
||||
Result := line;
|
||||
end;
|
||||
|
||||
begin
|
||||
Writeln(ReadLine(7, 'test'));
|
||||
Readln;
|
||||
end.
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
defmodule LineReader do
|
||||
def get_line(filename, line) do
|
||||
File.stream!(filename)
|
||||
|> Stream.with_index
|
||||
|> Stream.filter(fn {_value, index} -> index == line-1 end)
|
||||
|> Enum.at(0)
|
||||
|> print_line
|
||||
end
|
||||
defp print_line({value, _line_number}), do: String.trim(value)
|
||||
defp print_line(_), do: {:error, "Invalid Line"}
|
||||
end
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
-module( read_a_specific_line ).
|
||||
|
||||
-export( [from_file/2, task/0] ).
|
||||
|
||||
from_file( File, N ) -> line_nr( N, read_a_file_line_by_line:into_list(File) ).
|
||||
|
||||
task() ->
|
||||
Lines = read_a_file_line_by_line:into_list( "read_a_specific_line.erl" ),
|
||||
Line_7 = line_nr( 7, Lines ),
|
||||
Line_7.
|
||||
|
||||
|
||||
|
||||
line_nr( N, Lines ) ->
|
||||
try
|
||||
case lists:nth( N, Lines )
|
||||
of "\n" -> erlang:exit( empty_line )
|
||||
; Line -> Line
|
||||
end
|
||||
|
||||
catch
|
||||
_Type:Error0 ->
|
||||
Error = line_nr_error( Error0 ),
|
||||
io:fwrite( "Error: ~p~n", [Error] ),
|
||||
erlang:exit( Error )
|
||||
|
||||
end.
|
||||
|
||||
line_nr_error( function_clause ) -> too_few_lines_in_file;
|
||||
line_nr_error( Error ) -> Error.
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
open System
|
||||
open System.IO
|
||||
|
||||
[<EntryPoint>]
|
||||
let main args =
|
||||
let n = Int32.Parse(args.[1]) - 1
|
||||
use r = new StreamReader(args.[0])
|
||||
let lines = Seq.unfold (
|
||||
fun (reader : StreamReader) ->
|
||||
if (reader.EndOfStream) then None
|
||||
else Some(reader.ReadLine(), reader)) r
|
||||
let line = Seq.nth n lines // Seq.nth throws an ArgumentException,
|
||||
// if not not enough lines available
|
||||
Console.WriteLine(line)
|
||||
0
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
USING: continuations fry io io.encodings.utf8 io.files kernel
|
||||
math ;
|
||||
IN: rosetta-code.nth-line
|
||||
|
||||
: nth-line ( path encoding n -- str/f )
|
||||
[ f ] 3dip '[
|
||||
[ _ [ drop readln [ return ] unless* ] times ]
|
||||
with-return
|
||||
] with-file-reader ;
|
||||
|
||||
: nth-line-demo ( -- )
|
||||
"input.txt" utf8 7 nth-line [ "line not found" ] unless*
|
||||
print ;
|
||||
|
||||
MAIN: nth-line-demo
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
MODULE SAMPLER !To sample a record from a file. SAM00100
|
||||
CONTAINS SAM00200
|
||||
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
|
||||
Careful. Some compilers get confused over the function name's usage. SAM00400
|
||||
INTEGER N !The desired record number. SAM00500
|
||||
INTEGER F !Of this file. SAM00600
|
||||
CHARACTER*(*) IS !Stashed here. SAM00700
|
||||
INTEGER I,L !Assistants. SAM00800
|
||||
IS = "" !Clear previous content, even if null...SAM00900
|
||||
IF (N.LE.0) THEN !Start on errors. SAM01000
|
||||
WRITE (GETREC,1) "!No record",N !Could never be found. SAM01100
|
||||
1 FORMAT (A,1X,I0) !Message, number. SAM01200
|
||||
ELSE IF (F.LE.0) THEN !Obviously wrong? SAM01300
|
||||
WRITE (GETREC,1) "!No unit number",F!Positive is valid. SAM01400
|
||||
ELSE IF (LEN(IS).LE.0) THEN !Space awaits? SAM01500
|
||||
WRITE (GETREC,1) "!String size",LEN(IS) !Nope. SAM01600
|
||||
ELSE !Otherwise, there is hope. SAM01700
|
||||
REWIND (F) !Clarify the file position. SAM01800
|
||||
DO I = 1,N - 1 !Grind up to the desired record. SAM01900
|
||||
READ (F,2,END=3) !Ignoring any content. SAM02000
|
||||
END DO !Are we there yet? SAM02100
|
||||
READ (F,2,END = 3) L,IS(1:MIN(L,LEN(IS))) !At last. SAM02200
|
||||
2 FORMAT (Q,A) !Q = characters yet unread. SAM02300
|
||||
IF (L.LT.LEN(IS)) IS(L + 1:) = "" !Clear the tail. SAM02400
|
||||
IF (L.GT.LEN(IS)) THEN !Now for more silliness.SAM02500
|
||||
WRITE (GETREC,1) "+Length",L !Too long to fit in IS. SAM02600
|
||||
ELSE IF (L.LE.0) THEN !A zero-length record SAM02700
|
||||
WRITE (GETREC,1) "+Null" !Is not the same SAM02800
|
||||
ELSE IF (IS.EQ."") THEN !As a record SAM02900
|
||||
WRITE (GETREC,1) "+Blank",L !Containing spaces. SAM03000
|
||||
ELSE !But otherwise, SAM03100
|
||||
WRITE (GETREC,1) " Length",L !Note the leading space.SAM03200
|
||||
END IF !Righto, we've decided. SAM03300
|
||||
END IF !And, no more options. SAM03400
|
||||
RETURN !So, done. SAM03500
|
||||
3 WRITE (GETREC,1) "!End on read",I !An alternative ending. SAM03600
|
||||
END FUNCTION GETREC !That was interesting. SAM03700
|
||||
END MODULE SAMPLER !Just a sample of possibility. SAM03800
|
||||
SAM03900
|
||||
PROGRAM POKE POK00100
|
||||
USE SAMPLER POK00200
|
||||
INTEGER ENUFF !Some sizes. POK00300
|
||||
PARAMETER (ENUFF = 666) !Sufficient? POK00400
|
||||
CHARACTER*(ENUFF) STUFF !Lots of memory these days. POK00500
|
||||
CHARACTER*20 RESULT POK00600
|
||||
INTEGER MSG,F !I/O unit numbers. POK00700
|
||||
MSG = 6 !Standard output. POK00800
|
||||
F = 10 !Chooose a unit number. POK00900
|
||||
WRITE (MSG,*) " To select record 7 from a disc file." POK01000
|
||||
POK01100
|
||||
WRITE (MSG,*) "As a FORMATTED file." POK01200
|
||||
OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ") POK01300
|
||||
RESULT = GETREC(7,F,STUFF) POK01400
|
||||
WRITE (MSG,1) "Result",RESULT POK01500
|
||||
WRITE (MSG,1) "Record",STUFF POK01600
|
||||
1 FORMAT (A,":",A) POK01700
|
||||
POK01800
|
||||
CLOSE (F) POK01900
|
||||
WRITE (MSG,*) "As a random-access unformatted file." POK02000
|
||||
OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ", POK02100
|
||||
1 ACCESS="DIRECT",FORM="UNFORMATTED",RECL=82) !Not 80! POK02200
|
||||
STUFF = "Cleared." POK02300
|
||||
READ (F,REC = 7,ERR = 666) STUFF(1:80) POK02400
|
||||
WRITE (MSG,1) "Record",STUFF(1:80) POK02500
|
||||
STOP POK02600
|
||||
666 WRITE (MSG,*) "Can't get the record!" POK02700
|
||||
END !That was easy. POK02800
|
||||
|
|
@ -0,0 +1 @@
|
|||
READ (F'7) STUFF(1:80)
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
READ (F,REC = 7,ERR = 666, IOSTAT = IOSTAT) STUFF(1:80)
|
||||
666 IF (IOSTAT.NE.0) THEN
|
||||
WRITE (MSG,*) "Can't get the record: code",IOSTAT
|
||||
ELSE
|
||||
WRITE (MSG,1) "Record",STUFF(1:80)
|
||||
END IF
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
' FB 1.05.0 Win64
|
||||
|
||||
Open "input.txt" For Input As #1
|
||||
Dim line_ As String
|
||||
Dim count As Integer = 0
|
||||
While Not Eof(1)
|
||||
Line Input #1, line_ '' read each line
|
||||
count += 1
|
||||
If count = 7 Then
|
||||
line_ = Trim(line_, Any !" \t") '' remove any leading or trailing spaces or tabs
|
||||
If line_ = "" Then
|
||||
Print "The 7th line is empty"
|
||||
Else
|
||||
Print "The 7th line is : "; line_
|
||||
End If
|
||||
Exit While
|
||||
End If
|
||||
Wend
|
||||
If count < 7 Then
|
||||
Print "There are only"; count; " lines in the file"
|
||||
End If
|
||||
Close #1
|
||||
Print
|
||||
Print "Press any key to quit"
|
||||
Sleep
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
nthLine[filename, lineNum] :=
|
||||
{
|
||||
line = nth[lines[filenameToURL[filename]], lineNum-1]
|
||||
if line != undef
|
||||
return line
|
||||
else
|
||||
{
|
||||
println["The file $filename does not contain a line number $lineNum"]
|
||||
return undef
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
window 1
|
||||
|
||||
long i = 1
|
||||
Str255 s, lineSeven
|
||||
CFURLRef url
|
||||
|
||||
url = openpanel 1, @"Select text file"
|
||||
if ( url )
|
||||
open "I", 2, url
|
||||
while ( not eof(2) )
|
||||
line input #2, s
|
||||
if ( i == 7 )
|
||||
lineSeven = s : break
|
||||
end if
|
||||
i++
|
||||
wend
|
||||
close 2
|
||||
|
||||
if ( lineSeven[0] )
|
||||
print lineSeven
|
||||
else
|
||||
print "File did not contain seven lines, or line was empty."
|
||||
end if
|
||||
end if
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if line, err := rsl("input.txt", 7); err == nil {
|
||||
fmt.Println("7th line:")
|
||||
fmt.Println(line)
|
||||
} else {
|
||||
fmt.Println("rsl:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func rsl(fn string, n int) (string, error) {
|
||||
if n < 1 {
|
||||
return "", fmt.Errorf("invalid request: line %d", n)
|
||||
}
|
||||
f, err := os.Open(fn)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
bf := bufio.NewReader(f)
|
||||
var line string
|
||||
for lnum := 0; lnum < n; lnum++ {
|
||||
line, err = bf.ReadString('\n')
|
||||
if err == io.EOF {
|
||||
switch lnum {
|
||||
case 0:
|
||||
return "", errors.New("no lines in file")
|
||||
case 1:
|
||||
return "", errors.New("only 1 line")
|
||||
default:
|
||||
return "", fmt.Errorf("only %d lines", lnum)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if line == "" {
|
||||
return "", fmt.Errorf("line %d empty", n)
|
||||
}
|
||||
return line, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
def line = null
|
||||
new File("lines.txt").eachLine { currentLine, lineNumber ->
|
||||
if (lineNumber == 7) {
|
||||
line = currentLine
|
||||
}
|
||||
}
|
||||
println "Line 7 = $line"
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
main :: IO ()
|
||||
main = do contents <- readFile filename
|
||||
case drop 6 $ lines contents of
|
||||
[] -> error "File has less than seven lines"
|
||||
l:_ -> putStrLn l
|
||||
where filename = "testfile"
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
procedure main()
|
||||
write(readline("foo.bar.txt",7)|"failed")
|
||||
end
|
||||
|
||||
procedure readline(f,n) # return n'th line of file f
|
||||
f := open(\f,"r") | fail # open file
|
||||
every i := n & line := |read(f) \ n do i -:= 1 # <== here
|
||||
close(f)
|
||||
if i = 0 then return line
|
||||
end
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
readLine=: 4 :0
|
||||
(x-1) {:: <;.2 ] 1!:1 boxxopen y
|
||||
)
|
||||
|
|
@ -0,0 +1 @@
|
|||
$ cal 2011 > cal.txt
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
7 readLine 'cal.txt'
|
||||
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
require 'files' NB. required for versions before J701
|
||||
readLineT=: <:@[ {:: 'b'&freads@]
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package linenbr7;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class LineNbr7 {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File f = new File(args[0]);
|
||||
if (!f.isFile() || !f.canRead())
|
||||
throw new IOException("can't read " + args[0]);
|
||||
|
||||
BufferedReader br = new BufferedReader(new FileReader(f));
|
||||
try (LineNumberReader lnr = new LineNumberReader(br)) {
|
||||
String line = null;
|
||||
int lnum = 0;
|
||||
while ((line = lnr.readLine()) != null
|
||||
&& (lnum = lnr.getLineNumber()) < 7) {
|
||||
}
|
||||
|
||||
switch (lnum) {
|
||||
case 0:
|
||||
System.out.println("the file has zero length");
|
||||
break;
|
||||
case 7:
|
||||
boolean empty = "".equals(line);
|
||||
System.out.println("line 7: " + (empty ? "empty" : line));
|
||||
break;
|
||||
default:
|
||||
System.out.println("the file has only " + lnum + " line(s)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public final class ReadSpecificLineFromFile {
|
||||
|
||||
public static void main(String[] aArgs) throws IOException {
|
||||
String fileName = "input.txt";
|
||||
Path filePath = Path.of(fileName);
|
||||
|
||||
String seventhLine = Files.lines(filePath).skip(6).findFirst().orElse(ERROR_TOO_FEW_LINES);
|
||||
|
||||
String messageToUser = seventhLine.isBlank() ? ERROR_EMPTY_LINE : seventhLine;
|
||||
System.out.println(messageToUser);
|
||||
}
|
||||
|
||||
private static final String ERROR_TOO_FEW_LINES = "File has fewer than 7 lines";
|
||||
private static final String ERROR_EMPTY_LINE = "Line 7 is empty";
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Input - a line number to read, counting from 1
|
||||
# Output - a stream with 0 or 1 items
|
||||
def read_line:
|
||||
. as $in
|
||||
| label $top
|
||||
| foreach inputs as $line
|
||||
(0; .+1; if . == $in then $line, break $top else empty end) ;
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
$line | tonumber
|
||||
| if . > 0 then read_line
|
||||
else "$line (\(.)) should be a non-negative integer"
|
||||
end
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
$ jq -n -r 'range(0;20) | tostring' | jq --arg line 10 -n -R -r -f Read_a_specific_line_from_a_file.jq
|
||||
9
|
||||
|
|
@ -0,0 +1 @@
|
|||
open(readlines, "path/to/file")[7]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
function read_nth_lines(stream, num)
|
||||
for i = 1:num-1
|
||||
readline(stream)
|
||||
end
|
||||
result = readline(stream)
|
||||
print(result != "" ? result : "No such line.")
|
||||
end
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(0:"135-0.txt")7
|
||||
"will have to check the laws of the country where you are located before\r"
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(0:"135-0.txt")7-1
|
||||
"www.gutenberg.org. If you are not located in the United States, you\r"
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
// version 1.1.2
|
||||
|
||||
import java.io.File
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
/* The following code reads the whole file into memory
|
||||
and so should not be used for large files
|
||||
which should instead be read line by line until the
|
||||
desired line is reached */
|
||||
|
||||
val lines = File("input.txt").readLines()
|
||||
if (lines.size < 7)
|
||||
println("There are only ${lines.size} lines in the file")
|
||||
else {
|
||||
val line7 = lines[6].trim()
|
||||
if (line7.isEmpty())
|
||||
println("The seventh line is empty")
|
||||
else
|
||||
println("The seventh line is : $line7")
|
||||
}
|
||||
}
|
||||
|
||||
/* Note that 'input.txt' contains the eight lines:
|
||||
Line 1
|
||||
Line 2
|
||||
Line 3
|
||||
Line 4
|
||||
Line 5
|
||||
Line 6
|
||||
Line 7
|
||||
Line 8
|
||||
*/
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
local(f) = file('unixdict.txt')
|
||||
handle => { #f->close }
|
||||
local(this_line = string,line = 0)
|
||||
#f->forEachLine => {
|
||||
#line++
|
||||
#line == 7 ? #this_line = #1
|
||||
#line == 7 ? loop_abort
|
||||
}
|
||||
#this_line // 6th, which is the 7th line in the file
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
fileName$ ="F:\sample.txt"
|
||||
requiredLine =7
|
||||
|
||||
open fileName$ for input as #i
|
||||
f$ =input$( #i, lof( #i))
|
||||
close #i
|
||||
|
||||
line7$ =word$( f$, 7, chr$( 13))
|
||||
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
|
||||
|
||||
print line7$
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
function fileLine (lineNum, fileName)
|
||||
local count = 0
|
||||
for line in io.lines(fileName) do
|
||||
count = count + 1
|
||||
if count == lineNum then return line end
|
||||
end
|
||||
error(fileName .. " has fewer than " .. lineNum .. " lines.")
|
||||
end
|
||||
|
||||
print(fileLine(7, "test.txt"))
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
eln = 7; % extract line number 7
|
||||
line = '';
|
||||
fid = fopen('foobar.txt','r');
|
||||
if (fid < 0)
|
||||
printf('Error:could not open file\n')
|
||||
else
|
||||
n = 0;
|
||||
while ~feof(fid),
|
||||
n = n + 1;
|
||||
if (n ~= eln),
|
||||
fgetl(fid);
|
||||
else
|
||||
line = fgetl(fid);
|
||||
end
|
||||
end;
|
||||
fclose(fid);
|
||||
end;
|
||||
printf('line %i: %s\n',eln,line);
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
path := "file.txt":
|
||||
specificLine := proc(path, num)
|
||||
local i, input:
|
||||
for i to num do
|
||||
input := readline(path):
|
||||
if input = 0 then break; end if:
|
||||
end do:
|
||||
if i = num+1 then printf("Line %d, %s", num, input):
|
||||
elif i <= num then printf ("Line number %d is not reached",num): end if:
|
||||
end proc:
|
||||
|
|
@ -0,0 +1 @@
|
|||
If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
iter = io.lines 'test.txt'
|
||||
for i=0, 5
|
||||
error 'Not 7 lines in file' if not iter!
|
||||
|
||||
print iter!
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
def getline(fname, linenum)
|
||||
contents = null
|
||||
try
|
||||
contents = new(Nanoquery.IO.File).read()
|
||||
return contents[linenum]
|
||||
catch
|
||||
if contents = null
|
||||
throw new(Exception, "unable to read from file '" + fname + "'")
|
||||
else
|
||||
throw new(Exception, "unable to retrieve line " + linenum + " from file: not enough lines")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref symbols nobinary
|
||||
|
||||
parse arg inFileName lineNr .
|
||||
|
||||
if inFileName = '' | inFileName = '.' then inFileName = './data/input.txt'
|
||||
if lineNr = '' | lineNr = '.' then lineNr = 7
|
||||
|
||||
do
|
||||
lineTxt = readLine(inFileName, lineNr)
|
||||
say '<textline number="'lineNr.right(5, 0)'">'lineTxt'</textline>'
|
||||
catch ex = Exception
|
||||
ex.printStackTrace()
|
||||
end
|
||||
|
||||
return
|
||||
|
||||
-- =============================================================================
|
||||
-- NetRexx/Java programs don't have a special mechanism to seek to a specified line number
|
||||
-- the simple solution is to iterate through file. (Costly for very large files)
|
||||
method readLine(inFileName, lineNr) public static signals IOException, FileNotFoundException
|
||||
|
||||
lineReader = LineNumberReader(FileReader(File(inFileName)))
|
||||
notFound = isTrue
|
||||
lineTxt = ''
|
||||
loop label reading forever
|
||||
line = lineReader.readLine()
|
||||
select
|
||||
when lineReader.getLineNumber() = lineNr then do
|
||||
lineTxt = line
|
||||
notFound = isFalse
|
||||
leave reading -- terminate I/O loop
|
||||
end
|
||||
when line = null then do
|
||||
leave reading -- terminate I/O loop
|
||||
end
|
||||
otherwise nop
|
||||
end
|
||||
finally
|
||||
lineReader.close()
|
||||
end reading
|
||||
|
||||
if notFound then signal RuntimeException('File' inFileName 'does not contain line' lineNr.right(5))
|
||||
|
||||
return lineTxt
|
||||
|
||||
-- =============================================================================
|
||||
method isTrue() public static returns boolean
|
||||
return 1 == 1
|
||||
-- =============================================================================
|
||||
method isFalse() public static returns boolean
|
||||
return \(1 == 1)
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import strformat
|
||||
|
||||
proc readLine(f: File; num: Positive): string =
|
||||
for n in 1..num:
|
||||
try:
|
||||
result = f.readLine()
|
||||
except EOFError:
|
||||
raise newException(IOError, &"Not enough lines in file; expected {num}, found {n - 1}.")
|
||||
|
||||
let f = open("test.txt", fmRead)
|
||||
echo f.readLine(7)
|
||||
f.close()
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
let input_line_opt ic =
|
||||
try Some (input_line ic)
|
||||
with End_of_file -> None
|
||||
|
||||
let nth_line n filename =
|
||||
let ic = open_in filename in
|
||||
let rec aux i =
|
||||
match input_line_opt ic with
|
||||
| Some line ->
|
||||
if i = n then begin
|
||||
close_in ic;
|
||||
(line)
|
||||
end else aux (succ i)
|
||||
| None ->
|
||||
close_in ic;
|
||||
failwith "end of file reached"
|
||||
in
|
||||
aux 1
|
||||
|
||||
let () =
|
||||
print_endline (nth_line 7 Sys.argv.(1))
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
uses stringutil
|
||||
new Textarray t
|
||||
t.load "t.txt"
|
||||
print t.line 7
|
||||
' print t.lineCount
|
||||
del t
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
|
||||
|
||||
function fileLine ($lineNum, $file) {
|
||||
$count = 0;
|
||||
while (!feof($file)) {
|
||||
$count++;
|
||||
$line = fgets($file);
|
||||
if ($count == $lineNum) return $line;
|
||||
}
|
||||
die("Requested file has fewer than ".$lineNum." lines!");
|
||||
}
|
||||
|
||||
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
|
||||
if (!$fp) die("Input file not found!");
|
||||
echo fileLine(7, $fp);
|
||||
?>
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
declare text character (1000) varying, line_no fixed;
|
||||
|
||||
get (line_no);
|
||||
on endfile (f) begin;
|
||||
put skip list ('the specified line does not exist');
|
||||
go to next;
|
||||
end;
|
||||
|
||||
get file (f) edit ((text do i = 1 to line_no)) (L);
|
||||
|
||||
put skip list (text);
|
||||
next: ;
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
100H: /* READ A SPECIFIC LINE FROM A FILE */
|
||||
|
||||
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
|
||||
DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */
|
||||
DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */
|
||||
/* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
|
||||
BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
|
||||
/* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
|
||||
BDOS$P: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
|
||||
EXIT: PROCEDURE; CALL BDOS$P( 0, 0 ); END; /* CP/M SYSTEM RESET */
|
||||
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;
|
||||
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;
|
||||
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) ); END;
|
||||
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
|
||||
DECLARE N ADDRESS;
|
||||
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
|
||||
V = N;
|
||||
W = LAST( N$STR );
|
||||
N$STR( W ) = '$';
|
||||
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
|
||||
DO WHILE( ( V := V / 10 ) > 0 );
|
||||
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
|
||||
END;
|
||||
CALL PR$STRING( .N$STR( W ) );
|
||||
END PR$NUMBER;
|
||||
FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
|
||||
DECLARE FCB ADDRESS; /* FCB EXISTS */
|
||||
RETURN ( BDOS( 17, FCB ) < 4 );
|
||||
END FL$EXISTS ;
|
||||
FL$OPEN: PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB */
|
||||
DECLARE FCB ADDRESS;
|
||||
RETURN ( BDOS( 15, FCB ) < 4 );
|
||||
END FL$OPEN;
|
||||
FL$READ: PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB */
|
||||
DECLARE FCB ADDRESS;
|
||||
RETURN ( BDOS( 20, FCB ) = 0 );
|
||||
END FL$READ;
|
||||
FL$CLOSE: PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */
|
||||
DECLARE FCB ADDRESS;
|
||||
RETURN ( BDOS( 16, FCB ) < 4 );
|
||||
END FL$CLOSE;
|
||||
|
||||
PR$BYTE: PROCEDURE( B ); /* PRINT B EITHER AS A CHAR OR IN HEX */
|
||||
DECLARE B BYTE;
|
||||
PR$HEX: PROCEDURE( H ); /* PRINT A HEX DIGIT */
|
||||
DECLARE H BYTE;
|
||||
IF H < 10 THEN CALL PR$CHAR( H + '0' );
|
||||
ELSE CALL PR$CHAR( ( H - 10 ) + 'A' );
|
||||
END PR$HEX;
|
||||
IF B >= ' ' AND B < 7FH AND B <> '$' THEN DO;
|
||||
/* PRINTABLE CHAR AND NOT A $, SHOW AS A CHARACTER */
|
||||
CALL PR$CHAR( B );
|
||||
END;
|
||||
ELSE DO;
|
||||
/* NON-PRINTING CHAR OR $ - SHOW IN HEX */
|
||||
CALL PR$CHAR( '$' );
|
||||
CALL PR$HEX( SHR( B, 4 ) );
|
||||
CALL PR$HEX( B AND 0FH );
|
||||
END;
|
||||
END PR$BYTE;
|
||||
|
||||
/* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC. */
|
||||
/* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */
|
||||
/* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2 */
|
||||
/* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END */
|
||||
/* OF FCB2, SO WE NEED TO GET THE LINE NUMBER FROM FCB2 FIRST */
|
||||
|
||||
DECLARE FCB$SIZE LITERALLY '36'; /* SIZE OF A FCB */
|
||||
DECLARE FCB1 LITERALLY '5CH'; /* ADDRESS OF FIRST FCB */
|
||||
DECLARE FCB2 LITERALLY '6CH'; /* ADDRESS OF SECOND FCB */
|
||||
DECLARE DMA$BUFFER LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS */
|
||||
DECLARE DMA$SIZE LITERALLY '128'; /* SIZE OF THE DMA BUFFER */
|
||||
|
||||
DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE;
|
||||
|
||||
/* GET THE LINE NUMBER FROM THE SECOND PARAMETER */
|
||||
DECLARE LINE$NUMBER ADDRESS;
|
||||
LINE$NUMBER = 0;
|
||||
DO F$PTR = FCB2 + 1 TO FCB2 + 8;
|
||||
IF F$CHAR >= '0' AND F$CHAR <= '9' THEN DO;
|
||||
LINE$NUMBER = ( LINE$NUMBER * 10 ) + ( F$CHAR - '0' );
|
||||
END;
|
||||
END;
|
||||
/* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2 */
|
||||
DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 );
|
||||
F$CHAR = 0;
|
||||
END;
|
||||
|
||||
/* SHOW THE REQUIRED LINE FROM THE FILE, IF THE FILE AND LINE EXIST */
|
||||
IF NOT FL$EXISTS( FCB1 ) THEN DO; /* THE FILE DOES NOT EXIST */
|
||||
CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL;
|
||||
END;
|
||||
ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE */
|
||||
CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL;
|
||||
END;
|
||||
ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO FIND THE LINE */
|
||||
DECLARE LN ADDRESS, GOT$RCD BYTE, GOT$LINE BYTE, DMA$END ADDRESS;
|
||||
DMA$END = DMA$BUFFER + ( DMA$SIZE - 1 );
|
||||
GOT$RCD = FL$READ( FCB1 ); /* GET THE FIRST RECORD */
|
||||
GOT$LINE = FALSE;
|
||||
F$PTR = DMA$BUFFER;
|
||||
LN = 1;
|
||||
CALL PR$NUMBER( LINE$NUMBER ); CALL PR$STRING( .': <$' );
|
||||
DO WHILE( GOT$RCD AND LN <= LINE$NUMBER );
|
||||
IF F$PTR > DMA$END THEN DO;
|
||||
/* AT THE END OF THE BUFFER - GET THE NEXT RECORD */
|
||||
GOT$RCD = FL$READ( FCB1 );
|
||||
F$PTR = DMA$BUFFER;
|
||||
END;
|
||||
ELSE IF F$CHAR = NL$CHAR THEN DO; /* END OF LINE */
|
||||
LN = LN + 1;
|
||||
IF LN = LINE$NUMBER THEN GOT$LINE = TRUE;
|
||||
END;
|
||||
ELSE IF F$CHAR = EOF$CHAR THEN GOT$RCD = FALSE; /* END OF FILE */
|
||||
ELSE IF LN = LINE$NUMBER THEN CALL PR$BYTE( F$CHAR );
|
||||
F$PTR = F$PTR + 1;
|
||||
END;
|
||||
CALL PR$CHAR( '>' ); CALL PR$NL;
|
||||
/* SHOULD NOW HAVE EOF OR THE END OF THE REQUIRED LINE */
|
||||
IF NOT GOT$LINE THEN DO;
|
||||
/* COULDN'T READ THE SPECIFIED LINE */
|
||||
CALL PR$STRING( .'CANNOT READ LINE $' );
|
||||
CALL PR$NUMBER( LINE$NUMBER );
|
||||
END;
|
||||
/* CLOSE THE FILE */
|
||||
IF NOT FL$CLOSE( FCB1 ) THEN DO;
|
||||
CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL;
|
||||
END;
|
||||
END;
|
||||
|
||||
CALL EXIT;
|
||||
|
||||
EOF
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
Program FileTruncate;
|
||||
|
||||
uses
|
||||
SysUtils;
|
||||
|
||||
const
|
||||
filename = 'test';
|
||||
position = 7;
|
||||
|
||||
var
|
||||
myfile: text;
|
||||
line: string;
|
||||
counter: integer;
|
||||
|
||||
begin
|
||||
if not FileExists(filename) then
|
||||
begin
|
||||
writeln('Error: File does not exist.');
|
||||
exit;
|
||||
end;
|
||||
|
||||
Assign(myfile, filename);
|
||||
Reset(myfile);
|
||||
counter := 0;
|
||||
Repeat
|
||||
if eof(myfile) then
|
||||
begin
|
||||
writeln('Error: The file "', filename, '" is too short. Cannot read line ', position);
|
||||
Close(myfile);
|
||||
exit;
|
||||
end;
|
||||
inc(counter);
|
||||
readln(myfile);
|
||||
until counter = position - 1;
|
||||
readln(myfile, line);
|
||||
Close(myfile);
|
||||
writeln(line);
|
||||
end.
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
#!/usr/bin/perl -s
|
||||
# invoke as <scriptname> -n=7 [input]
|
||||
while (<>) { $. == $n and print, exit }
|
||||
die "file too short\n";
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
-->
|
||||
<span style="color: #004080;">object</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TEST.TXT"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">7</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #0000FF;">?</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">7</span><span style="color: #0000FF;">]</span>
|
||||
<span style="color: #008080;">else</span>
|
||||
<span style="color: #0000FF;">?</span><span style="color: #008000;">"no line 7"</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
-->
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TEST.TXT"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (shows -1 if past eof)</span>
|
||||
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
include ..\Utilitys.pmt
|
||||
|
||||
argument 1 get "r" fopen var f drop
|
||||
0
|
||||
7 for
|
||||
f fgets number? if f fclose exitfor else nip nip endif
|
||||
endfor
|
||||
print /# show -1 if past eof #/
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
(in "file.txt"
|
||||
(do 6 (line))
|
||||
(or (line) (quit "No 7 lines")) )
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
$file = Get-Content c:\file.txt
|
||||
if ($file.count -lt 7)
|
||||
{Write-Warning "The file is too short!"}
|
||||
else
|
||||
{
|
||||
$file | Where Readcount -eq 7 | set-variable -name Line7
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
Structure lineLastRead
|
||||
lineRead.i
|
||||
line.s
|
||||
EndStructure
|
||||
|
||||
Procedure readNthLine(file, n, *results.lineLastRead)
|
||||
*results\lineRead = 0
|
||||
While *results\lineRead < n And Not Eof(file)
|
||||
*results\line = ReadString(file)
|
||||
*results\lineRead + 1
|
||||
Wend
|
||||
|
||||
If *results\lineRead = n
|
||||
ProcedureReturn 1
|
||||
EndIf
|
||||
EndProcedure
|
||||
|
||||
Define filename.s = OpenFileRequester("Choose file to read a line from", "*.*", "All files (*.*)|*.*", 0)
|
||||
If filename
|
||||
Define file = ReadFile(#PB_Any, filename)
|
||||
If file
|
||||
Define fileReadResults.lineLastRead, lineToRead = 7
|
||||
If readNthLine(file, lineToRead, fileReadResults)
|
||||
MessageRequester("Results", fileReadResults\line)
|
||||
Else
|
||||
MessageRequester("Error", "There are less than " + Str(lineToRead) + " lines in file.")
|
||||
EndIf
|
||||
CloseFile(file)
|
||||
Else
|
||||
MessageRequester("Error", "Couldn't open file " + filename + ".")
|
||||
EndIf
|
||||
EndIf
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
with open('xxx.txt') as f:
|
||||
for i, line in enumerate(f):
|
||||
if i == 6:
|
||||
break
|
||||
else:
|
||||
print('Not 7 lines in file')
|
||||
line = None
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
from itertools import islice
|
||||
|
||||
with open('xxx.txt') as f:
|
||||
try:
|
||||
line = next(islice(f, 6, 7))
|
||||
except StopIteration:
|
||||
print('Not 7 lines in file')
|
||||
|
|
@ -0,0 +1 @@
|
|||
print open('xxx.txt').readlines()[:7][-1]
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
f = FREEFILE
|
||||
OPEN "input.txt" FOR INPUT AS #f
|
||||
|
||||
lineapedida = 7
|
||||
cont = 0
|
||||
DO WHILE NOT EOF(f)
|
||||
LINE INPUT #f, linea$
|
||||
cont = cont + 1
|
||||
IF cont = lineapedida THEN
|
||||
IF linea$ = "" THEN PRINT "The 7th line is empty" ELSE PRINT linea$
|
||||
EXIT DO
|
||||
END IF
|
||||
LOOP
|
||||
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
|
||||
CLOSE #1
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short
|
||||
Read 0 items
|
||||
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
|
||||
Read 1 item
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
x: pick read/lines request-file/only 7
|
||||
either x [print x] [print "No seventh line"]
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
/*REXX program reads a specific line from a file (and displays the length and content).*/
|
||||
parse arg FID n . /*obtain optional arguments from the CL*/
|
||||
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
|
||||
if n=='' | n=="," then n=7 /* " " " " " " */
|
||||
|
||||
if lines(FID)==0 then call ser "wasn't found." /*see if the file exists (or not). */
|
||||
|
||||
call linein FID, n-1 /*read the record previous to N. */
|
||||
if lines(FID)==0 then call ser "doesn't contain" N 'lines.'
|
||||
/* [↑] any more lines to read in file?*/
|
||||
|
||||
$=linein(FID) /*read the Nth record in the file. */
|
||||
|
||||
say 'File ' FID " line " N ' has a length of: ' length($)
|
||||
say 'File ' FID " line " N 'contents: ' $ /*display the contents of the Nth line.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
/*REXX program reads a specific line from a file (and displays the length and content).*/
|
||||
parse arg FID n . /*obtain optional arguments from the CL*/
|
||||
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
|
||||
if n=='' | n=="," then n=7 /* " " " " " " */
|
||||
|
||||
if lines(FID)==0 then call ser "wasn't found." /*see if the file exists (or not). */
|
||||
|
||||
do n-1
|
||||
call linein FID /*read all the lines previous to N. */
|
||||
end /*n-1*/
|
||||
|
||||
if lines(FID)==0 then call ser "doesn't contain" N 'lines.'
|
||||
/* [↑] any more lines to read in file?*/
|
||||
|
||||
$=linein(FID) /*read the Nth record in the file. */
|
||||
|
||||
say 'File ' FID " line " N ' has a length of: ' length($)
|
||||
say 'File ' FID " line " N 'contents: ' $ /*display the contents of the Nth line.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
#lang racket
|
||||
|
||||
;; simple, but reads the whole file
|
||||
(define s1 (list-ref (file->lines "some-file") 6))
|
||||
|
||||
;; more efficient: read and discard n-1 lines
|
||||
(define s2
|
||||
(call-with-input-file "some-file"
|
||||
(λ(i) (for/last ([line (in-lines i)] [n 7]) line))))
|
||||
|
|
@ -0,0 +1 @@
|
|||
say lines[6] // die "Short file";
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
>> x: pick read/lines %file.txt 7
|
||||
|
||||
case [
|
||||
x = none [print "File has less than seven lines"]
|
||||
(length? x) = 0 [print "Line 7 is empty"]
|
||||
(length? x) > 0 [print append "Line seven = " x]
|
||||
]
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
fp = fopen("C:\Ring\ReadMe.txt","r")
|
||||
n = 0
|
||||
|
||||
r = ""
|
||||
while isstring(r)
|
||||
while n < 8
|
||||
r = fgetc(fp)
|
||||
if r = char(10) n++ see nl
|
||||
else see r ok
|
||||
end
|
||||
end
|
||||
fclose(fp)
|
||||
|
|
@ -0,0 +1 @@
|
|||
seventh_line = open("/etc/passwd").each_line.take(7).last
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
fileName$ = "f:\sample.txt"
|
||||
requiredLine = 7
|
||||
open fileName$ for input as #f
|
||||
|
||||
for i = 1 to requiredLine
|
||||
if not(eof(#f)) then line input #f, a$
|
||||
next i
|
||||
close #f
|
||||
print a$
|
||||
end
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
use std::fs::File;
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::Error;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let path = Path::new("file.txt");
|
||||
let line_num = 7usize;
|
||||
let line = get_line_at(&path, line_num - 1);
|
||||
println!("{}", line.unwrap());
|
||||
}
|
||||
|
||||
fn get_line_at(path: &Path, line_num: usize) -> Result<String, Error> {
|
||||
let file = File::open(path).expect("File not found or cannot be opened");
|
||||
let content = BufReader::new(&file);
|
||||
let mut lines = content.lines();
|
||||
lines.nth(line_num).expect("No line found at that position")
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
if env::args().len() <= 1 {
|
||||
println!("At least a path to a file is needed: No file path given");
|
||||
return;
|
||||
} else {
|
||||
let path = &env::args().nth(1).expect("could not parse the path");
|
||||
let path = Path::new(&path);
|
||||
let mut line_num = 1usize;
|
||||
if let Some(arg) = env::args().nth(2) {
|
||||
line_num = arg.parse::<usize>().expect("Parsing line number failed");
|
||||
}
|
||||
print_line_at(&path, line_num);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_line_at(path: &Path, line_num: usize) {
|
||||
if line_num < 1 {
|
||||
panic!("Line number has to be > 0");
|
||||
}
|
||||
let line_num = line_num - 1;
|
||||
let file = File::open(path).expect("File not found or cannot be opened");
|
||||
let content = BufReader::new(&file);
|
||||
let mut lines = content.lines();
|
||||
let line = lines.nth(line_num).expect("No line found at given position");
|
||||
println!("{}", line.expect("None line"));
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
lines = #.readlines("test.txt")
|
||||
#.output("Seventh line of text:")
|
||||
? #.size(lines,1)<7
|
||||
#.output("is absent")
|
||||
!
|
||||
#.output(lines[7])
|
||||
.
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
val lines = io.Source.fromFile("input.txt").getLines
|
||||
val seventhLine = lines drop(6) next
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
var lines: Iterator[String] = _
|
||||
try {
|
||||
lines = io.Source.fromFile("input.txt").getLines drop(6)
|
||||
} catch {
|
||||
case exc: java.io.IOException =>
|
||||
println("File not found")
|
||||
}
|
||||
var seventhLine: String = _
|
||||
if (lines != null) {
|
||||
if (lines.isEmpty) println("too few lines in file")
|
||||
else seventhLine = lines next
|
||||
}
|
||||
if ("" == seventhLine) println("line is empty")
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
val file = try Left(io.Source.fromFile("input.txt")) catch {
|
||||
case exc => Right(exc.getMessage)
|
||||
}
|
||||
val seventhLine = (for(f <- file.left;
|
||||
line <- f.getLines.toStream.drop(6).headOption.toLeft("too few lines").left) yield
|
||||
if (line == "") Right("line is empty") else Left(line)).joinLeft
|
||||
|
|
@ -0,0 +1 @@
|
|||
sed -n 7p
|
||||
|
|
@ -0,0 +1 @@
|
|||
sed '7h;$!d;x;s/^$/Error: no such line/'
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
$ include "seed7_05.s7i";
|
||||
|
||||
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
|
||||
result
|
||||
var string: line is "";
|
||||
begin
|
||||
while lineNum > 1 and hasNext(aFile) do
|
||||
readln(aFile);
|
||||
decr(lineNum);
|
||||
end while;
|
||||
line := getln(aFile);
|
||||
end func;
|
||||
|
||||
const proc: main is func
|
||||
local
|
||||
var string: fileName is "input.txt";
|
||||
var file: aFile is STD_NULL;
|
||||
var string: line is "";
|
||||
begin
|
||||
aFile := open(fileName, "r");
|
||||
if aFile = STD_NULL then
|
||||
writeln("Cannot open " <& fileName);
|
||||
else
|
||||
line := getLine(aFile, 7);
|
||||
if eof(aFile) then
|
||||
writeln("The file does not have 7 lines");
|
||||
else
|
||||
writeln("The 7th line of the file is:");
|
||||
writeln(line);
|
||||
end if;
|
||||
end if;
|
||||
end func;
|
||||
|
|
@ -0,0 +1 @@
|
|||
put line 7 of file "example.txt" into theLine
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
func getNthLine(filename, n) {
|
||||
var file = File.new(filename);
|
||||
file.open_r.each { |line|
|
||||
Num($.) == n && return line;
|
||||
}
|
||||
warn "file #{file} does not have #{n} lines, only #{$.}\n";
|
||||
return nil;
|
||||
}
|
||||
|
||||
var line = getNthLine("/etc/passwd", 7);
|
||||
print line if defined line;
|
||||
|
|
@ -0,0 +1 @@
|
|||
line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue