Reading text from a file

From CodeCodex

Implementations[edit]

C[edit]

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++[edit]

#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[edit]

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[edit]

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

OCaml[edit]

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[edit]

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[edit]

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

Ruby[edit]

# 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[edit]

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

Visual Basic[edit]

 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[edit]

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