Fgets () -------------------------------------------- Char * fgets (char * s, int size, file * stream ); S is the buffer for saving the read content Size indicates the buffer size. Stream is a file pointer.Fgets () function Read the first line break it encountered; Or the maximum length of a buffer zone is one character less; Or read the end of the file. If the fgets () function completes a whole row before reaching the maximum number of buffers, it adds a line break before the null character of the string to mark the end of a row. # Include <stdio. h> # Include <stdlib. h> # Deprecision slen 256 Const char * errmesg [] = {"Usage: % s string filename]/n ", "Can't open file % s/n "};
Int main (int argc, char * argv []) { FILE * fp; Char line [SLEN]; If (argc! = 3) { Fprintf (stderr, errmesg [0], argv [0]); Exit (EXIT_FAILURE ); } If (fp = fopen (argv [2], "r") = NULL) { Fprintf (stderr, errmesg [1], argv [2]); Exit (EXIT_FAILURE ); }
While (fgets (line, SLEN-1, fp )! = NULL) // as long as it does not reach the end of the file, Print by the length of the SLEN-1 { If (strstr (line, argv [1])! = NULL) // strstr function searches for line Character arrays and Returns a null pointer if the string argv [1] is the same. Fputs (line, stdout ); }
Fclose (FP ); Return 0; } |