CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2005
    Posts
    331

    How to count number of lines in a text file

    Hi,

    I have a question about file i/o in C, just with text files not binary. How can I count the number of lines in the file pointed to by a FILE pointer?

    Thanks.

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: How to count number of lines in a text file

    Read entire file and count how many '\n' there are.

  3. #3
    Join Date
    Jan 2008
    Posts
    5

    Re: How to count number of lines in a text file

    or if you're reading the file anyway, and have a while loop for your getline function, just declare an int before the loop and use something like
    Code:
    int file_lines=0;
    while(myfile != eof){
    myfile.getline(your crap here);
    file_lines++;
    }
    at the end of your read loop you'll also have the number of lines stored in file_lines. Regular expressions are quite useful for such tasks.

  4. #4
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: How to count number of lines in a text file

    If you're using a FILE pointer, you can do the same technique RandomPerson said, except with the C file functions:
    Code:
    FILE * myFile = fopen("...", "r");
    
    int file_lines=0;
    char buffer[1024];
    
    while ( !feof(myFile) ){
        fgets(myFile, 1024, myFile);
        file_lines++;
    }
    The one problem with this approach is that if a line has more than 1024 characters on it, you'll get an incorrect number of lines.

  5. #5
    Join Date
    Mar 2008
    Posts
    7

    Re: How to count number of lines in a text file

    If you are on a linux/unix machine
    you could use the wc function with the -l option for the number of lines

    Code:
     char mystring[20];
     system("wc FileName -l > xyz"); //output the contents of the wc command to a file
     char delim=' ';         
     ifstream fileHandler; 
     fileHandler.open("xyz");  // opens the file
     fileHandler.getline(mystring,20,delim); //reads the first word of the file 
     fileHandler.close(); 
     int NumOfLines=atoi(mystring);
     system("rm xyz");
    Works for me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured