This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1 @@
{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]]Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.

View file

@ -0,0 +1,2 @@
---
note: Text processing

View file

@ -0,0 +1,11 @@
main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
DO
print(read string);
read(new line);
print(new line)
OD;
except logical file end:
SKIP
)

View file

@ -0,0 +1,18 @@
main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
DO
PROC raise page end = (REF FILE f) BOOL: ( except page end );
on page end(stand in, raise page end);
DO
print(read string);
read(new line);
print(new line)
OD;
except page end:
read(new page);
print(new page)
OD;
except logical file end:
SKIP
)

View file

@ -0,0 +1 @@
{ print $0 }

View file

@ -0,0 +1 @@
1

View file

@ -0,0 +1,18 @@
with Ada.Text_Io; use Ada.Text_Io;
procedure Read_Stream is
Line : String(1..10);
Length : Natural;
begin
while not End_Of_File loop
Get_Line(Line, Length); -- read up to 10 characters at a time
Put(Line(1..Length));
-- The current line of input data may be longer than the string receiving the data.
-- If so, the current input file column number will be greater than 0
-- and the extra data will be unread until the next iteration.
-- If not, we have read past an end of line marker and col will be 1
if Col(Current_Input) = 1 then
New_Line;
end if;
end loop;
end Read_Stream;

View file

@ -0,0 +1,26 @@
CONST BUFLEN=1024, EOF=-1
PROC consume_input(fh)
DEF buf[BUFLEN] : STRING, r
REPEAT
/* even if the line si longer than BUFLEN,
ReadStr won't overflow; rather the line is
"splitted" and the remaining part is read in
the next ReadStr */
r := ReadStr(fh, buf)
IF buf[] OR (r <> EOF)
-> do something
WriteF('\s\n',buf)
ENDIF
UNTIL r=EOF
ENDPROC
PROC main()
DEF fh
fh := Open('basicinputloop.e', OLDFILE)
IF fh
consume_input(fh)
Close(fh)
ENDIF
ENDPROC

View file

@ -0,0 +1,4 @@
Loop, Read, Input.txt, Output.txt
{
FileAppend, %A_LoopReadLine%`n
}

View file

@ -0,0 +1,11 @@
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1)
SYS "GetStdHandle", STD_OUTPUT_HANDLE TO @hfile%(2)
SYS "SetConsoleMode", @hfile%(1), 0
*INPUT 13
*OUTPUT 14
REPEAT
INPUT A$
PRINT A$
UNTIL FALSE

View file

@ -0,0 +1,43 @@
#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
// word by word
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
std::string word;
while (is >> word)
{
// send the word to the output iterator
*dest = word;
}
}
// line by line:
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
std::string line;
while (std::getline(is, line))
{
// store the line to the output iterator
*dest = line;
}
}
int main()
{
// 1) sending words from std. in std. out (end with Return)
read_words(std::cin,
std::ostream_iterator<std::string>(std::cout, " "));
// 2) appending lines from std. to vector (end with Ctrl+Z)
std::vector<std::string> v;
read_lines(std::cin, std::back_inserter(v));
return 0;
}

View file

@ -0,0 +1,26 @@
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
typedef std::istream_iterator<std::string> InIt;
std::copy(InIt(is), InIt(),
dest);
}
namespace detail
{
struct ReadableLine : public std::string
{
friend std::istream & operator>>(std::istream & is, ReadableLine & line)
{
return std::getline(is, line);
}
};
}
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
typedef std::istream_iterator<detail::ReadableLine> InIt;
std::copy(InIt(is), InIt(),
dest);
}

View file

@ -0,0 +1,32 @@
#include <stdlib.h>
#include <stdio.h>
char *get_line(FILE* fp)
{
int len = 0, got = 0, c;
char *buf = 0;
while ((c = fgetc(fp)) != EOF) {
if (got + 1 >= len) {
len *= 2;
if (len < 4) len = 4;
buf = realloc(buf, len);
}
buf[got++] = c;
if (c == '\n') break;
}
if (c == EOF && !got) return 0;
buf[got++] = '\0';
return buf;
}
int main()
{
char *s;
while ((s = get_line(stdin))) {
printf("%s",s);
free(s);
}
return 0;
}

View file

@ -0,0 +1,2 @@
(defn basic-input [fname]
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))

View file

@ -0,0 +1,5 @@
(defun basic-input (filename)
(with-open-file (stream (make-pathname :name filename) :direction :input)
(loop for line = (read-line stream nil nil)
while line
do (format t "~a~%" line))))

View file

@ -0,0 +1,8 @@
import tango.io.Console;
import tango.text.stream.LineIterator;
void main (char[][] args) {
foreach (line; new LineIterator!(char)(Cin.input)) {
// do something with each line
}
}

View file

@ -0,0 +1,8 @@
import tango.io.Console;
import tango.text.stream.SimpleIterator;
void main (char[][] args) {
foreach (word; new SimpleIterator!(char)(" ", Cin.input)) {
// do something with each word
}
}

View file

@ -0,0 +1,17 @@
program InputLoop;
{$APPTYPE CONSOLE}
uses SysUtils, Classes;
var
lReader: TStreamReader; // Introduced in Delphi XE
begin
lReader := TStreamReader.Create('input.txt', TEncoding.Default);
try
while lReader.Peek >= 0 do
Writeln(lReader.ReadLine);
finally
lReader.Free;
end;
end.

View file

@ -0,0 +1,236 @@
note
description : "{
There are several examples included, including input from a text file,
simple console input and input from standard input explicitly.
See notes in the code for details.
Examples were compile using Eiffel Studio 6.6 with only the default
class libraries.
}"
class APPLICATION
create
make
feature
make
do
-- These examples show non-console input (a plain text file)
-- with end-of-input handling.
read_lines_from_file
read_words_from_file
-- These examples use simplified input from 'io', that
-- handles the details of whether it's stdin or not
-- They terminate on a line (word) of "q"
read_lines_from_console_with_termination
read_words_from_console_with_termination
-- The next examples show reading stdin explicitly
-- as if it were a text file. It expects and end of file
-- termination and so will loop indefinitely unless reading
-- from a pipe or your console can send an EOF.
read_lines_from_stdin
read_words_from_stdin
-- These examples use simplified input from 'io', that
-- handles the details of whether it's stdin or not,
-- but have no explicit termination
read_lines_from_console_forever
read_words_from_console_forever
end
--|--------------------------------------------------------------
read_lines_from_file
-- Read input from a text file
-- Echo each line of the file to standard output.
--
-- Some language examples omit file open/close operations
-- but are included here for completeness. Additional error
-- checking would be appropriate in production code.
local
tf: PLAIN_TEXT_FILE
do
print ("Reading lines from a file%N")
create tf.make ("myfile") -- Create a file object
tf.open_read -- Open the file in read mode
-- The actual input loop
from
until tf.end_of_file
loop
tf.read_line
print (tf.last_string + "%N")
end
tf.close -- Close the file
end
--|--------------------------------------------------------------
read_words_from_file
-- Read input from a text file
-- Echo each word of the file to standard output on a
-- separate line.
--
-- Some language examples omit file open/close operations
-- but are included here for completeness. Additional error
-- checking would be appropriate in production code.
local
tf: PLAIN_TEXT_FILE
do
print ("Reading words from a file%N")
create tf.make ("myfile") -- Create a file object
tf.open_read -- Open the file in read mode
-- The actual input loop
from
until tf.end_of_file
loop
-- This instruction is the only difference between this
-- example and the read_lines_from_file example
tf.read_word
print (tf.last_string + "%N")
end
tf.close -- Close the file
end
--|--------------------------------------------------------------
read_lines_from_console_with_termination
-- Read lines from console and echo them back to output
-- until the line contains only the termination key 'q'
--
-- 'io' is acquired through inheritance from class ANY,
-- the top of all inheritance hierarchies.
local
the_cows_come_home: BOOLEAN
do
print ("Reading lines from console%N")
from
until the_cows_come_home
loop
io.read_line
if io.last_string ~ "q" then
the_cows_come_home := True
print ("Mooooo!%N")
else
print (io.last_string)
io.new_line
end
end
end
--|--------------------------------------------------------------
read_words_from_console_with_termination
-- Read words from console and echo them back to output, one
-- word per line, until the line contains only the
-- termination key 'q'
--
-- 'io' is acquired through inheritance from class ANY,
-- the top of all inheritance hierarchies.
local
the_cows_come_home: BOOLEAN
do
print ("Reading words from console%N")
from
until the_cows_come_home
loop
io.read_word
if io.last_string ~ "q" then
the_cows_come_home := True
print ("Mooooo!%N")
else
print (io.last_string)
io.new_line
end
end
end
--|--------------------------------------------------------------
read_lines_from_console_forever
-- Read lines from console and echo them back to output
-- until the program is terminated externally
--
-- 'io' is acquired through inheritance from class ANY,
-- the top of all inheritance hierarchies.
do
print ("Reading lines from console (no termination)%N")
from
until False
loop
io.read_line
print (io.last_string + "%N")
end
end
--|--------------------------------------------------------------
read_words_from_console_forever
-- Read words from console and echo them back to output, one
-- word per line until the program is terminated externally
--
-- 'io' is acquired through inheritance from class ANY,
-- the top of all inheritance hierarchies.
do
print ("Reading words from console (no termination)%N")
from
until False
loop
io.read_word
print (io.last_string + "%N")
end
end
--|--------------------------------------------------------------
read_lines_from_stdin
-- Read input from a stream on standard input
-- Echo each line of the file to standard output.
-- Note that we treat standard input as if it were a plain
-- text file
local
tf: PLAIN_TEXT_FILE
do
print ("Reading lines from stdin (EOF termination)%N")
tf := io.input
from
until tf.end_of_file
loop
tf.read_line
print (tf.last_string + "%N")
end
end
--|--------------------------------------------------------------
read_words_from_stdin
-- Read input from a stream on standard input
-- Echo each word of the file to standard output on a new
-- line
-- Note that we treat standard input as if it were a plain
-- text file
local
tf: PLAIN_TEXT_FILE
do
print ("Reading words from stdin (EOF termination)%N")
tf := io.input
from
until tf.end_of_file
loop
tf.read_line
print (tf.last_string + "%N")
end
end
end

View file

@ -0,0 +1,10 @@
procedure process_line_by_line(integer fn)
object line
while 1 do
line = gets(fn)
if atom(line) then
exit
end if
-- process the line
end while
end procedure

View file

@ -0,0 +1 @@
"file.txt" utf8 [ [ process-line ] each-line ] with-file-reader

View file

@ -0,0 +1,26 @@
class Main
{
public static Void main ()
{
// example of reading by line
str := "first\nsecond\nthird\nword"
inputStream := str.in
inputStream.eachLine |Str line|
{
echo ("Line is: $line")
}
// example of reading by word
str = "first second third word"
inputStream = str.in
word := inputStream.readStrToken // reads up to but excluding next space
while (word != null)
{
echo ("Word: $word")
inputStream.readChar // skip over the preceding space!
word = inputStream.readStrToken
}
}
}

View file

@ -0,0 +1,6 @@
4096 constant max-line
: read-lines
begin stdin pad max-line read-line throw
while pad swap \ addr len is the line of data, excluding newline
2drop
repeat ;

View file

@ -0,0 +1,20 @@
program BasicInputLoop
implicit none
integer, parameter :: in = 50, &
linelen = 1000
integer :: ecode
character(len=linelen) :: l
open(in, file="afile.txt", action="read", status="old", iostat=ecode)
if ( ecode == 0 ) then
do
read(in, fmt="(A)", iostat=ecode) l
if ( ecode /= 0 ) exit
write(*,*) trim(l)
end do
close(in)
end if
end program BasicInputLoop

View file

@ -0,0 +1,17 @@
package main
import (
"bufio"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
for {
s, err := in.ReadString('\n')
if err != nil {
break
}
_ = s
}
}

View file

@ -0,0 +1,5 @@
def lineMap = [:]
System.in.eachLine { line, i ->
lineMap[i] = line
}
lineMap.each { println it }

View file

@ -0,0 +1,11 @@
import System.IO
readLines :: Handle -> IO [String]
readLines h = do
s <- hGetContents h
return $ lines s
readWords :: Handle -> IO [String]
readWords h = do
s <- hGetContents h
return $ words s

View file

@ -0,0 +1,10 @@
CHARACTER name='myfile.txt', string*1000
OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)
DO line = 1, bytes ! loop terminates with end-of-file error at the latest
READ(FIle=name, IOStat=errorcode, ERror=9) string
WRITE(StatusBar) string
ENDDO
9 WRITE(Messagebox, Name) line, errorcode

View file

@ -0,0 +1,14 @@
link str2toks
# call either words or lines depending on what you want to do.
procedure main()
words()
end
procedure lines()
while write(read())
end
procedure words()
local line
while line := read() do line ? every write(str2toks())
end

View file

@ -0,0 +1,4 @@
#!/Applications/j602/bin/jconsole
NB. read input until EOF
((1!:1) 3)(1!:2) 4
exit ''

View file

@ -0,0 +1,10 @@
$ ./read-input-to-eof.ijs <<EOF
> abc
> def
> ghi
> now is the time for all good men ...
> EOF
abc
def
ghi
now is the time for all good men ...

View file

@ -0,0 +1,9 @@
import java.util.Scanner;
...
Scanner in = new Scanner(System.in);//stdin
//new Scanner(new FileInputStream(filename)) for a file
//new Scanner(socket.getInputStream()) for a network stream
while(in.hasNext()){
String input = in.next(); //in.nextLine() for line-by-line
//process the input here
}

View file

@ -0,0 +1,16 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
...
try{
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));//stdin
//new BufferedReader(new FileReader(filename)) for a file
//new BufferedReader(new InputStreamReader(socket.getInputStream())) for a network stream
while(inp.ready()){
String input = inp.readLine();//line-by-line only
//in.read() for character-by-character
//process the input here
}
} catch (IOException e) {
//There was an input error
}

View file

@ -0,0 +1,8 @@
var text_stream = WScript.StdIn;
var i = 0;
while ( ! text_stream.AtEndOfStream ) {
var line = text_stream.ReadLine();
// do something with line
WScript.echo(++i + ": " + line);
}

View file

@ -0,0 +1,16 @@
string sNOTECARD = "Input_Loop_Data_Source.txt";
default {
integer iNotecardLine = 0;
state_entry() {
llOwnerSay("Reading '"+sNOTECARD+"'");
llGetNotecardLine(sNOTECARD, iNotecardLine);
}
dataserver(key kRequestId, string sData) {
if(sData==EOF) {
llOwnerSay("EOF");
} else {
llOwnerSay((string)iNotecardLine+": "+sData);
llGetNotecardLine(sNOTECARD, ++iNotecardLine);
}
}
}

View file

@ -0,0 +1,5 @@
: read-lines do read . "\n" . eof if break then loop ;
: ==>contents
'< swap open 'fh set fh fin read-lines fh close ;
'file.txt ==>contents

View file

@ -0,0 +1,9 @@
filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
while not(eof(#f))
line input #f, t$
print t$
wend
close #f
end

View file

@ -0,0 +1 @@
while [not eof?] [print readline]

View file

@ -0,0 +1,6 @@
lines = {}
str = io.read()
while str do
table.insert(lines,str)
str = io.read()
end

View file

@ -0,0 +1,5 @@
lines = {}
for line in io.lines() do
table.insert(lines, line) -- add the line to the list of lines
end

View file

@ -0,0 +1,10 @@
fn ReadAFile FileName =
(
local in_file = openfile FileName
while not eof in_file do
(
--Do stuff in here--
print (readline in_file)
)
close in_file
)

View file

View file

@ -0,0 +1,3 @@
stream = OpenRead["file.txt"];
While[a != EndOfFile, Read[stream, Word]];
Close[stream]

View file

@ -0,0 +1,31 @@
:- module input_loop.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
main(!IO) :-
io.stdin_stream(Stdin, !IO),
io.stdout_stream(Stdout, !IO),
read_and_print_lines(Stdin, Stdout, !IO).
:- pred read_and_print_lines(io.text_input_stream::in,
io.text_output_stream::in, io::di, io::uo) is det.
read_and_print_lines(InFile, OutFile, !IO) :-
io.read_line_as_string(InFile, Result, !IO),
(
Result = ok(Line),
io.write_string(OutFile, Line, !IO),
read_and_print_lines(InFile, OutFile, !IO)
;
Result = eof
;
Result = error(IOError),
Msg = io.error_message(IOError),
io.stderr_stream(Stderr, !IO),
io.write_string(Stderr, Msg, !IO),
io.set_exit_status(1, !IO)
).

View file

@ -0,0 +1,23 @@
PROCEDURE ReadName (VAR str : ARRAY OF CHAR);
VAR n : CARDINAL;
ch, endch : CHAR;
BEGIN
REPEAT
InOut.Read (ch);
Exhausted := InOut.EOF ();
IF Exhausted THEN RETURN END
UNTIL ch > ' '; (* Eliminate whitespace *)
IF ch = '[' THEN endch := ']' ELSE endch := ch END;
n := 0;
REPEAT
InOut.Read (ch);
Exhausted := InOut.EOF ();
IF Exhausted THEN RETURN END;
IF n <= HIGH (str) THEN str [n] := ch ELSE ch := endch END;
INC (n)
UNTIL ch = endch;
IF n <= HIGH (str) THEN str [n-1] := 0C END;
lastCh := ch
END ReadName;

View file

@ -0,0 +1,14 @@
MODULE Output EXPORTS Main;
IMPORT Rd, Wr, Stdio;
VAR buf: TEXT;
<*FATAL ANY*>
BEGIN
WHILE NOT Rd.EOF(Stdio.stdin) DO
buf := Rd.GetLine(Stdio.stdin);
Wr.PutText(Stdio.stdout, buf);
END;
END Output.

View file

@ -0,0 +1,8 @@
$fh = fopen($filename, 'r');
if ($fh) {
while (!feof($fh)) {
$line = rtrim(fgets($fh)); # removes trailing newline
# process $line
}
fclose($fh);
}

View file

@ -0,0 +1 @@
$lines = file($filename);

View file

@ -0,0 +1 @@
$contents = file_get_contents($filename);

View file

@ -0,0 +1,6 @@
open FH, "< $filename" or die "can't open file: $!";
while (my $line = <FH>) {
chomp $line; # removes trailing newline
# process $line
}
close FH or die "can't close file: $!";

View file

@ -0,0 +1 @@
@lines = <FH>;

View file

@ -0,0 +1,3 @@
while (<>) {
# $_ contains a line
}

View file

@ -0,0 +1,4 @@
(in "file.txt"
(make
(until (eof)
(link (line)) ) ) )

View file

@ -0,0 +1,6 @@
my_file = open(filename, 'r')
try:
for line in my_file:
pass # process line, includes newline
finally:
my_file.close()

View file

@ -0,0 +1,5 @@
from __future__ import with_statement
with open(filename, 'r') as f:
for line in f:
pass # process line, includes newline

View file

@ -0,0 +1,2 @@
line = my_file.readline() # returns a line from the file
lines = my_file.readlines() # returns a list of the rest of the lines from the file

View file

@ -0,0 +1,3 @@
import fileinput
for line in fileinput.input():
pass # process line, includes newline

View file

@ -0,0 +1 @@
lines <- readLines("file.txt")

View file

@ -0,0 +1,3 @@
do while stream(stdin, "State") <> "NOTREADY"
call charout ,charin(stdin)
end

View file

@ -0,0 +1,5 @@
/* -- AREXX -- */
do until eof(stdin)
l = readln(stdin)
say l
end

View file

@ -0,0 +1,6 @@
/*REXX program to read from the (console) default input stream until nul*/
do until _==''
parse pull _
end /*until ...*/
exit /*stick a fork in it, we're done.*/

View file

@ -0,0 +1,2 @@
#lang racket
(copy-port (current-input-port) (current-output-port))

View file

@ -0,0 +1,4 @@
stream = $stdin
stream.each do |line|
# process line
end

View file

@ -0,0 +1,2 @@
# Create an array of lengths of every line.
ary = stream.map {|line| line.chomp.length}

View file

@ -0,0 +1,3 @@
scala.io.Source.fromFile(filename).getLines.foreach {
line => // do something
}

View file

@ -0,0 +1,3 @@
scala.io.Source.fromPath(filename).getLines().foreach {
line => // do something
}

View file

@ -0,0 +1,3 @@
|f|
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .

View file

@ -0,0 +1,5 @@
set fh [open $filename]
while {[gets $fh line] != -1} {
# process $line
}
close $fh

View file

@ -0,0 +1,6 @@
set fh [open $filename]
set data [read $fh]
close $fh
foreach line [split $data \n] {
# process line
}