Difference between revisions of "Reading text from a file"

From CodeCodex

(Implementations)
m (Java: fixing a few errors in this)
Line 51: Line 51:
 
===Java===
 
===Java===
 
<pre class="java">
 
<pre class="java">
    try {
+
    try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
+
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line;
+
        String line = null;
        while (line != null){ // read until end of file  
+
        while (line != null){ // read until end of file  
            line=FileIn.readLine(); // read file contents  
+
            line=in.readLine(); // read file contents  
            System.out.println(line);// Prints the line
+
            System.out.println(line);// Prints the line
        }
+
        }
        in.close();// Closes the Buffered Reader
+
        in.close();// Closes the Buffered Reader
    }  
+
    }  
    catch (IOException e) {
+
    catch (IOException e) {
        System.err.println(Error);
+
        System.err.println(e);
    }
+
    }
 
</pre>
 
</pre>
  

Revision as of 02:25, 5 February 2012

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(file));
		        String line = null;
		        while (line != null){ // read until end of file 
		             line=in.readLine(); // read file contents 
		             System.out.println(line);// Prints the line
		        }
		        in.close();// Closes the Buffered Reader
		    } 
		    catch (IOException e) {
		         System.err.println(e);
		    }

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