The wc2 example relies on concepts and examples introduced previously. Please review the following as needed:
The word count utility, wc, has been included in most POSIX operating systems (Unix, Linux, and macOS) from their earliest days. We used a simplified version of wc in chapter 3 as a switch-statement example. We restore some of the removed functionality in this version, allowing users to enter multiple file names on the command line. The program will print count totals for all files.
This example demonstrates a situation where creating a single input stream object is convenient. The program alternately opens and closes the stream to process multiple files.
#include <iostream> #include <fstream> #include <iomanip> using namespace std; int main(int argc, char* argv[]) // (a) { ifstream file; // (b) int total_chars = 0; // (c) int total_lines = 0; int total_words = 0; for (int i = 1; i < argc; i++) // (d) { file.open(argv[i]); // (e) if (! file.good()) // (f) continue; int chars = 0; // (g) int lines = 1; int words = 0; bool in_word = false; int c; while ((c = file.get()) != EOF) // (h) { chars++; switch (c) { case '\n': lines++; // fall through case ' ': case '\t': in_word = false; break; default: if (! in_word) { in_word = true; words++; } break; } } file.close(); // (i) total_chars += chars; // (j) total_lines += words; total_words += lines; cout << setw(8) << lines << // (k) setw(8) << words << setw(8) << chars << " " << argv[i] << endl; } if (argc > 2) // (l) cout << setw(8) << total_lines << setw(8) << total_words << setw(8) << total_chars << " total" << endl; return 0; } |
|