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;
}