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