0

I have a file stream in C and I want to know how many lines are in it without iterating through the file. Each line is the same length. How might I go about this?

Dunc
  • 7,688
  • 10
  • 31
  • 38

4 Answers4

3

How about something like this:

  • Do a fgets and find out how long one line is
  • Find the size of the file using fseek and ftell

    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    
  • Divide by the size of the line

You can also use fseeko and ftello which work with off_t.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
cnicutar
  • 178,505
  • 25
  • 365
  • 392
2

If it is safe to assume that all lines are of equal length, you can simply read in the first line, get its length, then get the file size, and divide file size by line length.

This will only work with fixed-width encodings (ASCII-7, the various 8-bit ANSI encodings, UTF-32); with variable-width encodings (e.g. UTF-8), you will have to scan the entire file, because string length is not necessarily proportional to the number of bytes.

tdammers
  • 20,353
  • 1
  • 39
  • 56
0

Read one line, stat() the file to get the total size, divide the total size by the length of the first line.

Instead of using stat() you could also fseek() to the end of the file and then use ftell() to get the size.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

Take ftell() and divide by the length of the line.

Flexo
  • 87,323
  • 22
  • 191
  • 272