Count the number of lines in a text file
From CodeCodex
Contents |
[edit] Implementations
[edit] Perl
my $line_count = 0;
open my $fh, '<', $filename or die qq{Cannot open "$filename": $!};
while ( sysread $fh, my $buffer, 4096 ) {
$line_count += ($buffer =~ tr/\n//);
}
close $fh;
Original Source: Perl documentation (perlfaq5)
[edit] PHP
Extremely simple PHP sample to count and return the number of lines in a text file. The output can be customized to suit your own requirements.
<?php $file = "somefile.txt"; $lines = count(file($file)); echo "There are $lines lines in $file"; ?>
[edit] Python
filename = "somefile.txt" myfile = open(filename) lines = len(myfile.readlines()) print "There are %d lines in %s" % (lines, filename)
[edit] Ruby
filename = "somefile.txt"
count = IO.readlines(filename).size
puts "There are #{count} lines in #{filename}";
[edit] Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
public class ReadFile {
public static int countLines(final String filename) {
StreamTokenizer st = null;
Reader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
st = new StreamTokenizer(reader);
while (st.nextToken() != StreamTokenizer.TT_EOF) {
}
} catch (final IOException ioe) {
System.err.println("IOException occurred:");
ioe.printStackTrace();
} finally {
try {
reader.close();
} catch (final IOException ignored) {
// deliberately ignored
}
}
return st.lineno();
}
public static void main(final String arrrggghh[]) {
final int lines = ReadFile.countLines("/Cucu_Video_log.txt");
System.out.println("file has " + lines + " lines in it");
}
}

