count.cpp 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // count.cpp -- counting characters in a list of files
  2. #include <iostream>
  3. #include <fstream>
  4. #include <cstdlib> // or stdlib.h
  5. int main(int argc, char * argv[])
  6. {
  7. using namespace std;
  8. if (argc == 1) // quit if no arguments
  9. {
  10. cerr << "Usage: " << argv[0] << " filename[s]\n";
  11. exit(EXIT_FAILURE);
  12. }
  13. ifstream fin; // open stream
  14. long count;
  15. long total = 0;
  16. char ch;
  17. for (int file = 1; file < argc; file++)
  18. {
  19. fin.open(argv[file]); // connect stream to argv[file]
  20. if (!fin.is_open())
  21. {
  22. cerr << "Could not open " << argv[file] << endl;
  23. fin.clear();
  24. continue;
  25. }
  26. count = 0;
  27. while (fin.get(ch))
  28. count++;
  29. cout << count << " characters in " << argv[file] << endl;
  30. total += count;
  31. fin.clear(); // needed for some implementations
  32. fin.close(); // disconnect file
  33. }
  34. cout << total << " characters in all files\n";
  35. return 0;
  36. }