473,765 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Counting lines in a text file

Hi,

Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must be
an easier way??

Thanks in advance

Feb 15 '06 #1
7 13506
Mark..... <MA*********@HO TMAIL.COM> wrote:
Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must be
an easier way??


I don't see why there "must" be an easier way. Just call ReadLine on a
TextReader until it returns null, incrementing a counter each time. How
could it be much easier?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 15 '06 #2
Mark..... wrote:
Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must
be an easier way??


Hi Mark. A loop is probably the best way to do this, and is really simple.
Because lines are of unpredictable length, without any kind of metadata
stored with the file it's impossible to determine its line count without
reading every byte. If you want to do it in the least possible code, you
could use an expression like this, at the expense of a great deal of
additional memory for large files:

new StreamReader("f ile.txt").ReadT oEnd().Split(ne w char[] {'\n'}).Length

--
Derrick Coetzee, MCAD, MSFT (Speech Server)
This posting is provided "AS IS" with no warranties, and confers no
rights. Use of included code samples are subject to the terms
specified at http://www.microsoft.com/info/cpyright.htm
Feb 15 '06 #3
Jon Skeet [C# MVP] <sk***@pobox.co m> wrote:
I don't see why there "must" be an easier way. Just call ReadLine on a
TextReader until it returns null, incrementing a counter each time. How
could it be much easier?


Sorry, that really wasn't meant to come over as aggressively as it did.
Sincere apologies. Put it down to lousy sinuses at the moment :(

(It's still a pretty easy way of counting lines in a file though :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 15 '06 #4
> new StreamReader("f ile.txt").ReadT oEnd().Split(ne w char[] {'\n'}).Length

Hehe, I though about suggesting this, but just didn't have the guts to write
such a line of code! :-)
Feb 15 '06 #5
All the other comments should be the answer to your literal question.
However, it occured to me, are you trying to get file size? If so there IS a
better way. Take a look at the FileInfo.Length in the System.IO namespace.

--
-Demetri
"Mark....." wrote:
Hi,

Can someone tell me the easiest way to count the number of lines in a
text file?

I can write a loop to do this but it seems cumbersome.... there must be
an easier way??

Thanks in advance

Feb 15 '06 #6
Thanks for responses..very helpful

Feb 16 '06 #7
bek
1 New Member
I have the same problem, except that I need to know the number of lines in a text file so that I know what to set my maximum on my progressbar to. It seems really inefficient to count to the end to get the max, then count to the end again to process the data.

Anyone have any alternative suggestions? Seems like I read something about this many years ago and someone had come up with an answer.

Thanks,
bek
May 3 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3386
by: Sam Lowry | last post by:
Greetings. I am trying to do something which should elementary for Perl, but I have only been able to find bits and pieces on it. When I put the bits together they do not work. Maybe I am going in the wrong direction. I want to count several strings of text in a file (security.txt) and output the counts with a brief description of each. I have tried specifying the descriptions (name) and the strings (exe) in the array within the perl...
19
5698
by: Alex Vinokur | last post by:
Is there any tool to count C-program lines except comments? Thanks, ===================================== Alex Vinokur mailto:alexvn@connect.to http://mathforum.org/library/view/10978.html news://news.gmane.org/gmane.comp.lang.c++.perfometer =====================================
5
2847
by: Anders K. Jacobsen [DK] | last post by:
Hi We have a rather large asp.net project with serveral utility projects (written in C#). Is there at tool out there which can give an estimate of the total amount of code lines all projects results in? thanks in regads Anders
1
6929
by: j | last post by:
Hi, I've been trying to do line/character counts on documents that are being uploaded. As well as the "counting" I also have to remove certain sections from the file. So, firstly I was working with uploaded MS WORD .doc files. Using code like that below: strLine = sr.ReadLine While Not IsNothing(strLine) 'Not eof If Trim(strLine) <> "" Then 'Not blank
4
1816
by: Peter | last post by:
Currently I'm using the method below, is there someting more efficient?: Imports System.IO Public Class CountLine Public Shared Function CountLines(ByVal FileName As String) As Integer Dim fs As IO.FileStream Dim sr As IO.StreamReader Dim Result As Integer Try fs = New IO.FileStream( _
5
7704
by: andy.lee23 | last post by:
hi im having trouble counting lines in a text file, i have the following code int node1, node2, i; char name; float value; ifstream fin; fin.open(OpenDialog1->FileName.c_str()); i=1;
10
1516
by: cj | last post by:
I'm writing a TCP/IP server app that will have many simultaneous connections. The main thread listens for new connections and starts a thread to handle each requested connection. These are short lived threads that get a request and return a reply and end. Can the main thread tell me how many connection threads are currently running at any given time? I'd like to have a label on the main form to show how many connections the server is...
7
2116
by: peraklo | last post by:
Hello, there is another problem i am facing. i have a text file which is about 15000 lines big. i have to cut the last 27 lines from that file and create a new text file that contans those 27 lines. and after that save both of those files... since that is a big block of text (15000 lines) i thint that it is a big job to look for a keyword... so my question is this exactly: how do i do this:
7
1653
by: tiredMike | last post by:
Hi, I want to count lines in a text file in the format below: 255.000000,148.000000,0.000000,0.000000 255.000000,229.000000,0.000000,0.000000 255.000000,215.000000,0.000000,0.000000 37.000000,0.000000,0.000000,0.000000 71.000000,0.000000,0.000000,50.000000
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7375
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.