Difference between revisions of "Reading text from a file"

From CodeCodex

(c++ example added)
Line 14: Line 14:
  
 
printf ("%s\n", buff);
 
printf ("%s\n", buff);
 +
</HIGHLIGHTSYNTAX>
 +
 +
===C++===
 +
<HIGHLIGHTSYNTAX language="c++">
 +
    #include <fstream>
 +
    //using namespace std;
 +
    string line;
 +
    ifstream in("filename.txt");
 +
    if (!in) { cerr << "Unable to read from file ..." << endl; } else {
 +
      while (!in.eof() ) {
 +
        getline(in, line);
 +
        cout << line << endl;
 +
      }
 +
    }
 +
    // Note: file is automatically closed, when current scope is left
 
</HIGHLIGHTSYNTAX>
 
</HIGHLIGHTSYNTAX>
  
Line 110: Line 125:
  
 
[[Category:C]]
 
[[Category:C]]
 +
[[Category:C++]]
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:Objective Caml]]
 
[[Category:Objective Caml]]

Revision as of 10:31, 26 November 2009

Implementations

C

<HIGHLIGHTSYNTAX language="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); </HIGHLIGHTSYNTAX>

C++

<HIGHLIGHTSYNTAX language="c++">

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

</HIGHLIGHTSYNTAX>

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

<highlightsyntax language="perl"> open my $fh, '<', $filename or die qq{Cannot open "$filename": $!};

  1. Whole file as string

my $whole_file; {

   local $/;
   $whole_file = <$fh>;

}

  1. Do something

close $fh; </highlightsyntax>

<highlightsyntax language="perl"> open my $fh, '<', $filename or die qq{Cannot open "$filename": $!};

  1. One line at a time

while ( my $line = <$fh> ) { # Do something }

close $fh; </highlightsyntax>

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

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