c - How does this code counting the number of characters, lines, and words work? -


while (fgets(line, max_line_len-1, infile) != null) {     num_lines += 1;     num_chars += strlen(line);     if (strncmp(line, "", max_line_len) != 0) {         num_words++;     } } 

the whole program counts number of words. chunk of code increases line number of text , count words, don't know what's going on here. how work?

strlen( line ) 

give number of characters in line. (check man strlen.)

num_chars += strlen( line ) 

add number num_chars.

strncmp( line, "", max_line_len ) 

compare contents of line empty string (but on safe side, not read more max_line_len characters of line, in case not null-terminated). return 0 if equal. (for further details, refer man strncmp.)

if (strncmp(line, "", max_line_len) != 0) {     num_words++; } 

add 1 num_words if line not equal empty string.

note num_words misnomer, there no word counting going on here, counting of non-empty lines.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -