Gets a method for the number of rows in a file _c language

Source: Internet
Author: User

The first of these methods

Idea: Read the characters in a file one by one and compare it to \ n.

Copy Code code 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;
}

The second method
Using Fgets. Fgets prototype: Char *fgets (char *s, int size, FILE *stream), fgets can read up to size-1 characters, the remaining one is reserved for the, that is, always to reserve a bit. Also note: Fgets stops this read when he encounters \ n. If you can drop \ n in an array, you will only be able to read it next time, but to be sure, if you put it on the next read, \ n is definitely the first one, so that the next time you can read only \ n, it is automatically added. The rest of the content will have to be read next time. Then we find the rules! Which is always on the top of the first.

Copy Code code 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.