-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path17.39.cpp
41 lines (39 loc) · 997 Bytes
/
17.39.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
/*
* Exercise 17.39: Write your own version of the seek program presented in this
* section.
*
* By Faisal Saadatmand
*/
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char **argv)
{
if (argc != 2) {
std::cerr << "Usage: " << *argv << " <filename>\n";
return EXIT_FAILURE;
}
std::fstream inOut(*++argv,
std::fstream::ate | std::fstream::in | std::fstream::out);
if (!inOut) {
std::cerr << "Cannot open file" << *++argv << '\n';
return EXIT_FAILURE;
}
auto end_mark = inOut.tellg(); // original EOF position
inOut.seekg(0, std::fstream::beg);
std::size_t count = 0;
std::string line;
while (inOut && inOut.tellg() != end_mark
&& std::getline(inOut, line)) {
count += line.size() + 1; // 1 for newline char
auto mark = inOut.tellg(); // read postion
inOut.seekp(0, std::fstream::end);
inOut << count;
if (mark != end_mark)
inOut << " ";
inOut.seekg(mark);
}
inOut.seekp(0, std::fstream::end);
inOut << "\n";
return 0;
}