Thread: Count number of lines in a text file

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    242

    Count number of lines in a text file

    Erm, I'm trying to think of a way to count the number of lines in a text file.
    Well, I thought of
    while( fgets()... == '\n') counter++;
    am I right? BTW, does fgets exist in C#?

    Any suggestions/corrections?

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    If the textfile aint too big and/or you don't care about a slight performance hit you could split each line:
    Code:
    int NrOfLines = System.IO.File.ReadAllText("MyFile.txt").Split(new string[] { "\n" }, System.StringSplitOptions.None).Length;
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Location
    USA
    Posts
    24

    Talking

    Magos is the man!

    Been wondering about the address of text streams and lines in files with regarding the \n character for some time myself. Very simple and to the point. Excellent!!

    Thank you very much.
    Last edited by TheRaven; 04-30-2008 at 01:49 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading text file by line number
    By whiskedaway in forum C++ Programming
    Replies: 13
    Last Post: 06-16-2009, 10:09 AM
  2. Issue w/ Guess My Number Program
    By mkylman in forum C++ Programming
    Replies: 5
    Last Post: 08-23-2007, 01:31 AM
  3. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM