How to obtain the number of lines of a file

Source: Internet
Author: User

Method 1

Train of Thought: Read the characters in the file one by one, and then compare it with \ n.

CopyCode The Code is as follows: # include <stdio. h>
# Include <string. h>
# Include <errno. h>

Int main (INT argc, char * argv [])
{
File * FP;
Int n = 0;
Int ch;

If (FP = fopen (argv [1], "R +") = NULL)
{
Fprintf (stderr, "Open File 1.C error! % S \ n ", strerror (errno ));
}

While (CH = fgetc (FP ))! = EOF)
{
If (CH = '\ n ')
{
N ++;
}
}

Fclose (FP );
Printf ("% d \ n", N );
Return 0;
}

Method 2
Use fgets. Fgets prototype: char * fgets (char * s, int size, file * stream); fgets can read a maximum of size-1 characters, the remaining one is reserved for \ 0, that is, it is always reserved for \ 0. At the same time, you should also note that when fgets encounters \ n, this read will be stopped. If \ n can be put down in the array, read \ n; otherwise, it can only be read for the next time, but it is certain that, if it is placed in the next read, \ n must be the first, so that only \ n can be read next time and \ 0 will be automatically added. The remaining content must be read again. Now we can find the rule! That is, \ n is always on the first digit of \ 0.

Copy code The Code is as follows: # include <stdio. h>
# Include <string. h>
# Include <errno. h>

Int main (INT argc, char * argv [])
{
File * FP;
Int n = 0;
Char buffer [3];

If (FP = fopen (argv [1], "R +") = NULL)
{
Fprintf (stderr, "Open File 1.C error! % S \ n ", strerror (errno ));
}

While (fgets (buffer, 3, FP ))! = NULL)
{
If (buffer [strlen (buffer)-1] = '\ n ')
{
N ++;
}
}

Fclose (FP );
Printf ("% d \ n", N );
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.