forked from Light-City/CPlusPlusThings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
c++_example1.cpp
68 lines (57 loc) · 1.99 KB
/
c++_example1.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
//
// Created by light on 19-12-12.
//
#include <iostream>
#include <vector>
#include <cstring>
#include <fstream>
using namespace std;
vector<string> read_lines_from_file(string &file_name) {
vector<string> lines;
string line;
ifstream file_handle (file_name.c_str());
// file_handle.peek()!=EOF 解决多读一行问题
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
getline(file_handle, line);
lines.push_back(line);
}
file_handle.close();
return lines;
}
vector<string> * read_lines_from_file1(string &file_name) {
vector<string> * lines;
string line;
ifstream file_handle (file_name.c_str());
// file_handle.peek()!=EOF
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
getline(file_handle, line);
lines->push_back(line);
}
file_handle.close();
return lines;
}
vector<string> * read_lines_from_file1_1(string &file_name) {
vector<string> * lines=new vector<string>;
string line;
ifstream file_handle (file_name.c_str());
while (file_handle.good() && !file_handle.eof() && file_handle.peek()!=EOF) {
getline(file_handle, line);
lines->push_back(line);
}
file_handle.close();
return lines;
}
int main() {
// get file name from the first argument
string file_name ("/home/light/CLionProjects/Morden_C++/CMakeLists.txt");
int count = read_lines_from_file(file_name).size();
cout << "File " << file_name << " contains " << count << " lines.";
cout<<endl;
// string file_name1 ("/home/light/CLionProjects/Morden_C++/CMakeLists.txt");
// int count1 = read_lines_from_file1(file_name1)->size();
// cout << "File " << file_name << " contains " << count1 << " lines.";
string file_name1 ("/home/light/CLionProjects/Morden_C++/CMakeLists.txt");
int count1 = read_lines_from_file1_1(file_name1)->size();
cout << "File " << file_name << " contains " << count1 << " lines.";
return 0;
}