I recently read in detail the usage of the scanf () function and found that it is more complicated than printf. The usage of the scanf () function family is demonstrated here. Take fscanf () as an example to scan text files and print them row by row.
/* Test_scanf.c ** scanf () fscanf () usage example. * Scan ASCII text files by line and ignore empty lines (only rows containing carriage return/line break ). */# Include <stdio. h> # include <stdlib. h> # include <string. h> # define buffer_size 20int main (INT argc, char * argv []) {char line [buffer_size + 1]; char cmd [80]; /* const */INT I = 0; file * FP; int ret; char C1; FP = fopen ("test.txt", "rb"); If (! FP) {perror ("test.txt"); exit (-1);} fseek (FP, 0l, seek_set);/* e.g. "% 80 [^ \ r \ n] % C" */sprintf (CMD, "% d [^ \ r \ n] % C", buffer_size ); printf ("["); While (1) {C1 = '\ 0'; ret = fscanf (FP, CMD, line, & C1); If (ret = EOF) break; else if (ret = 0) {/* eat another '\ R' or' \ n '. e.g. '\ r \ n' for DOS. */ret = fscanf (FP, "% * C"); continue;} for (I = 0; I <buffer_size; I ++) {If (line [I] = '\ 0') break; printf ("% C", line [I]);} if (C1 = '\ n' | C1 =' \ R') printf ("] \ n ["); else/* incomplete line */fseek (FP, -1l, seek_cur);/* repeat it */} printf ("\ n"); fclose (FP); Return 0;}/** gcc-wall test_scanf.c */
Note the following:
- Leave enough buffer. For the buffer specified for fscanf (), at least one byte is reserved at the end, because fscanf () may be filled with null characters.
- "% 80 [^ \ r \ n] % C" indicates that characters other than '\ R' and' \ n' are read, until '\ R' or' \ n' is read (but '\ R' and' \ n' are reserved for the next read ), then read another character (this character must be '\ R' or' \ n ). Another case is: read characters that are not '\ R' or' \ n' until they are fully 80 characters and then read one character. The symbol % [...] is the mode between '[' and ']', and the ^ symbol is a logical inversion.
- "% * C" indicates reading a character without any processing. Note that there is an asterisk.
- Different platforms have different processing methods for line breaks. Specifically, Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ R '. In this example, a text file is opened in binary mode.
- The returned value of fscanf () is 0, probably because '\ n' in' \ r \ n' is encountered, or empty rows are encountered.