-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount.cpp
48 lines (37 loc) · 955 Bytes
/
count.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// C++ Primer Plus example list 17.17
//count.cpp -- counting characters in a list of files
#include <iostream>
#include <fstream>
#include <cstdlib> //for exit()
int main(int argc, char* argv[])
{
using namespace std;
if (argc == 1) //quit if no argument
{
cerr << "Usage: " << argv[0] << " filename[s]\n";
exit(EXIT_FAILURE);
}
ifstream fin; //open stream
long count;
long total = 0;
char ch;
for (int file = 1; file < argc; file++)
{
fin.open(argv[file]); //connect stream to argv[file]
if (!fin.is_open())
{
cerr << "Could not open " << argv[file] << endl;
fin.clear();
continue;
}
count = 0;
while (fin.get(ch))
count++;
cout << count << " characters in " << argv[file] << endl;
total += count;
fin.clear(); //needed for some implementations
fin.close();
}
cout << total << " characters in all files\n";
return 0;
}