Technology
 

Read file

From Programmer's Wiki

Contents

[edit] C

This article is missing a code example in the C language.

[edit] Java

In Java, you should always have this method inside a try catch block.

try{
	BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
}catch(IOException ex){
	System.out.println("Error reading file!");
}

[edit] Groovy

This article is missing a code example in the Groovy language.

[edit] Perl

#!/usr/bin/perl

# open file
open(FILE, "data.txt") or die("Unable to open file");



# read file into an array
@data = <FILE>;

close(FILE);

[edit] PHP

Reading from file:

if ( !($fp = @fopen('myfile.txt', 'r')) ) // r = read mode
    echo "Can't open myfile.txt (permission problem?)";
while ($line = fgets($fp, 4096)) { // reads 1 line or 4096 bytes
    echo $line . '<br>';
}
fclose($fp); // closes the file

Overwriting a file:

$fp = fopen('myfile.txt', 'w'); // r = write mode
fputs($fp, 'Hello World!'; // writes 'Hello World!'
fclose($fp);

Adding 1 line to a file:

$fp = fopen('myfile.txt', 'a'); // a = append mode
fputs($fp, 'Hello World!'; // appends 'Hello World!'
fclose($fp);

[edit] Python

f = open(filename, 'r')
data = f.read()
f.close()

[edit] Ruby

This article is missing a code example in the Ruby language.


[edit] See Also