Thread: lines in a file

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    36

    lines in a file

    OK last query of theday.

    Is there a way to obtain the number of lines in a file?

    I'm using

    Code:
    fstream finput;
    finput.open(sourceFileName, ios::in);
    read my file.

    I could just loop through to the end and increase a counter but this seems very inefficient, so thought there must be a better way

    Cheers

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I could just loop through to the end and increase a counter but this seems very inefficient
    Yes, that's pretty much the way you do it.

    Perhaps you should consider another approach, one which say doesn't rely on knowing the number of lines in advance. That way, you only read the file once instead of twice.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317
    Just a quick note. I have been messing around with compiler options and the __LINE__ macro gives the line# on which it is placed I tried this

    Code:
     
    unsigned long test=(unsigned long)__LINE__; cout<<test+otherfile; return 0;} //for main
    and then did a similar thing in each of the header files with a global variable. granted it counts white space and blank lines as well so it prolly isn't what your looking for but I just thought it was cool
    Last edited by manofsteel972; 09-29-2004 at 01:51 PM.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  4. #4
    Registered User
    Join Date
    May 2004
    Posts
    36
    Thanks for the response.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM