Wikia

Programmer's Wiki

Read file

Talk0
385pages on
this wiki

Contents

C Edit

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

Java Edit

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!");
}

Groovy Edit

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

Perl Edit

#!/usr/bin/perl

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



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

close(FILE);

PHP Edit

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);

Python Edit

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

Ruby Edit

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


See Also Edit

Advertisement | Your ad here

Photos

Add a Photo
28photos on this wiki
See all photos >

Recent Wiki Activity

See more >

Around Wikia's network

Random Wiki