-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
98 lines (73 loc) · 1.85 KB
/
main.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
static int byte_count(const std::string& filename) { //function to count bytes
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
std::cerr << "error" << "\n";
return -1;
}
file.seekg(0, std::ios::end);
int bytes = file.tellg();
file.close();
return bytes;
}
static int word_count(const std::string& filename) { //function to count words
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error!" << filename << "\n";
return -1;
}
int words = 0;
std::string read_word;
while (file >> read_word) {
words++;
}
file.close();
return words;
}
static int line_count(const std::string& filename) { //function to count lines
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error!" << filename << "\n";
return -1;
}
int lines = 0;
std::string read;
while (std::getline(file, read)) {
lines++;
}
file.close();
return lines;
}
int main(int argc, char* argv[]) { //argc is number of cmd line args and argc is array of pointer containing the args
if (argc != 3) {
std::cerr << argv[0] << " test.txt" << "\n"; //argv[0] is set to name of program file by default
std::cerr << "Options: \n";
std::cerr << " -b Count bytes \n";
std::cerr << " -w Count words \n";
std::cerr << " -l Count lines \n";
return 1;
}
std::string option = argv[1]; //second cmd ard is set for options
std::string filename = argv[2]; //third cmd arg is set to filename (here its test.txt)
int count = 0;
if (option == "-b") {
count = byte_count(filename);
}
else if (option == "-w") {
count = word_count(filename);
}
else if (option == "-l") {
count = line_count(filename);
}
else {
std::cerr << "Invalid !!" << option << "\n";
return 1;
}
if (count >= 0) {
std::cout << count << "\n";
}
return 0;
}