Most POSIX operating systems (Unix, Linux, and macOS) include the word count utility, wc. The text's previous version, wc.cpp, introduced the underlying counting problem and developed the counting algorithms but presented an incomplete version of the utility. The following version still lacks some options but authentically demonstrates iterating through files, opening and closing them as they are processed.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(int argc, char* argv[])
{
ifstream file;
int total_chars = 0;
int total_lines = 0;
int total_words = 0;
for (int i = 1; i < argc; i++)
{
file.open(argv[i]);
if (! file.good())
continue;
int chars = 0;
int lines = 1;
int words = 0;
bool in_word = false;
int c; |
while ((c = file.get()) != EOF) { chars++; switch (c) { case '\n': lines++; // fall through case ' ': case '\t': in_word = false; break; default: if (! in_word) { in_word = true; words++; } break; } } // end while |
file.close(); total_chars += chars; total_lines += words; total_words += lines; cout << setw(8) << lines << setw(8) << words << setw(8) << chars << " " << argv[i] << endl; } // end for if (argc > 2) cout << setw(8) << total_lines << setw(8) << total_words << setw(8) << total_chars << " total" << endl; return 0; } |
(a) | (b) | (c) |
View | Download | Comments |
---|---|---|
wc2.cpp | wc2.cpp | A program reading and processing multiple files one character at a time. The program uses a single stream object alternately opening and closing the files it reads. |