Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Number Of Lines without Reading File To End

Tags:

c#

text

algorithm

Is there a way to get Number of Lines within a Large Text file ,but without Reading the File content or reading file to end and Counting++.

Maybe there are some File Attributes ,but cannot find it out at all . Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it might be stupid to read first all Content than read it Again to Display the raw text at user.

bests

like image 329
Rosmarine Popcorn Avatar asked Sep 26 '11 13:09

Rosmarine Popcorn


2 Answers

No. You have to read the file. Consider storing it at the beginning of the file or in a separate file when you write the file if you want to find it quickly without counting.

Note that you can stream the file, and it's surprisingly fast:

int count = File.ReadLines(path).Count();

Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it might be stupid to read first all Content than read it Again to Display the raw text at user.

Oh, just get the file size and the length of each line in bytes and keep a cumulative count of the number of bytes processed so far.

like image 127
jason Avatar answered Oct 14 '22 11:10

jason


No, there is no other way.

A file is not line based (or even character based), so there is no meta information about the number of lines (or even number of characters). The only meta data about the content is the length in bytes.

If you have some additional information about the file, for example that each line is exactly the same length, and it uses an 8-bit encoding so that the number of characters is the same as the number of bytes, you could calculate the number of lines from the file size.

like image 20
Guffa Avatar answered Oct 14 '22 09:10

Guffa