• C

returning number of lines in a file?

The following statement reads from a file and outout the first 24 lines. However, i need to find the (%) read. So in order to find the % i need to get the total number of lines in the file . Is there any function which does that?
This is my statement.
Thanks in advance,

 while ( fgets( line, LINELEN, fp ) ){ /* more input */
              if ( num_of_lines == PAGELEN ) { /* full screen? */
                   reply = see_more(fp_tty); /* NEW: pass FILE * */
                   if ( reply == 0 ) /* n: done */
                           break;
                   num_of_lines -= reply; /* reset count */
              }
              if ( fputs( line, stdout ) == EOF ) /* show line*/
                   exit(1); /* or die */
              num_of_lines++; /* count it */
       }
Carl3003Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
call rewind(fp) after the first while.
0
 
Jaime OlivaresSoftware ArchitectCommented:
If your file has variable lenght lines, then there is not a function to give you number of lines. But you can give % read in this manner.
- Obtain total file length (T).
- Read every line and ACUMMULATE line lenghts in a variable (R)
- Your % read is R/T
0
 
Carl3003Author Commented:
Here comes my problem,
If i read the file once, I can not read it again.I do not know why. But here is an exammple.

while ( fgets( line, LINELEN, fp ) )
{

              total_lines++; /* count it */         
  }

then the next while loop would not work..
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Carl3003Author Commented:
thanks, that worked...
0
 
MysidiaCommented:
fseek(fp, 0L, SEEK_SET);
while (fgets( line, LINELEN, fp ))  total_lines++;
0
 
Jaime OlivaresSoftware ArchitectCommented:
Have you solved your problem?
0
 
Carl3003Author Commented:
yes, i realized that i could reopen the file again but rewind(fp) worked for me as well..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.