Difference between revisions of "Reading text from a file"

From CodeCodex

(Erlang)
(Implementations)
Line 123: Line 123:
 
   # handle file IO errors here
 
   # handle file IO errors here
 
end
 
end
 +
</pre>
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
set f [open "file.txt" r]
 +
set fd [read $f]
 +
close $f
 
</pre>
 
</pre>
  
Line 152: Line 159:
 
[[Category:Python]]
 
[[Category:Python]]
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 +
[[Category:Tcl]]
 
[[Category:Visual Basic]]
 
[[Category:Visual Basic]]
 
[[Category:Zsh]]
 
[[Category:Zsh]]
 
[[Category:I/O]]
 
[[Category:I/O]]

Revision as of 18:21, 18 February 2011

Implementations

C

FILE *f;

f = fopen ("path/to/file.ext", "r");
while (!feof (f))
{
    c = fgetc (f);
    buff[i++] = c;
}
fclose (f);

buff[i-1] = '\0';

printf ("%s\n", buff);

C++

#include <fstream>
    #include <iostream>
    #include <string>

    std::string line;
    std::ifstream in("filename.txt");
    if (!in) { std::cerr << "Unable to read from file ..." << std::endl; } else {
      while (!in.eof() ) {
        std::getline(in, line);
        std::cout << line << std::endl;
      }
    }
    // Note: file is automatically closed, when current scope is left

Erlang

read_text_file(Filename) ->
    {ok, IoDevice} = file:open(Filename, [read]),
    read_text(IoDevice),
    file:close(IoDevice).

read_text(IoDevice) ->
    case file:read_line(IoDevice) of
        {ok, Line} -> io:format("~s", [Line]),
                      read_text(IoDevice);
        eof        -> ok
    end.

Java

    try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String line;
        while (line != null){ // read until end of file 
             line=FileIn.readLine(); // read file contents 
             System.out.println(line);// Prints the line
        }
        in.close();// Closes the Buffered Reader
    } 
    catch (IOException e) {
         System.err.println(Error);
    }

OCaml

The following higher-order function applies the given function "process" to each line of the file "filename":

# let process_file process filename =
    let ch = open_in filename in
    try while true do process(input_line ch) done
    with End_of_file -> close_in ch;;
val process_file : (string -> 'a) -> string -> unit = <fun>

Perl

open my $fh, '<', $filename or die qq{Cannot open "$filename": $!};

# Whole file as string
my $whole_file;
{
    local $/;
    $whole_file = <$fh>;
}

# Do something

close $fh;
open my $fh, '<', $filename or die qq{Cannot open "$filename": $!};

# One line at a time
while ( my $line = <$fh> ) {
	# Do something
}

close $fh;

Python

# get contents of file as a list, one line per element
data = open('/path/to/file').readlines()

Ruby

# get contents of file as 1 string
begin
  file_string = File.read("/path/to/file")
rescue Exception => e
  # handle file IO errors here
end

# get contents of file as array split on newlines
begin
  file_array = File.readlines("/path/to/file")
rescue Exception => e
  # handle file IO errors here
end

Tcl

set f [open "file.txt" r]
set fd [read $f]
close $f

Visual Basic

 Dim FileName as String = "c:\somefile.txt"
 Open FileName For Input As #1
 Do Until EOF(1)
   Dim ThisLine as String
   ThisLine = LineInput(1)
 Loop
 Close(1)

Zsh

while read i
do
  print $i
done < /path/to/file