libostd/examples/stream2.cc

88 lines
1.8 KiB
C++
Raw Normal View History

2017-05-03 02:14:27 +02:00
/** @example stream2.cc
*
* An example of using streams to process strings, including some
* standard range algorithm use.
*/
#include <vector>
2016-01-31 23:19:23 +01:00
#include <ostd/algorithm.hh>
#include <ostd/string.hh>
2016-02-02 00:10:05 +01:00
#include <ostd/io.hh>
2016-01-31 23:19:23 +01:00
using namespace ostd;
int main() {
writeln("writing sample file...");
2017-02-16 20:39:05 +01:00
file_stream wtest{"test.txt", stream_mode::WRITE};
2016-01-31 23:19:23 +01:00
2017-01-30 00:54:06 +01:00
std::string smpl =
"This is a test file for later read.\n"
"It contains some sample text in order to see whether "
"things actually read correctly.\n\n\n"
""
"This is after a few newlines. The file continues here.\n"
"The file ends here.\n";
2016-01-31 23:19:23 +01:00
copy(iter(smpl), wtest.iter());
2016-01-31 23:19:23 +01:00
wtest.close();
2017-02-16 20:39:05 +01:00
file_stream test{"test.txt"};
2016-01-31 23:19:23 +01:00
writeln("## WHOLE FILE READ ##\n");
auto fr = test.iter();
writefln(
"-- str beg --\n%s-- str end --",
std::string{fr.iter_begin(), fr.iter_end()}
);
2016-01-31 23:19:23 +01:00
test.seek(0);
writeln("\n## PART FILE READ ##\n");
auto fr2 = test.iter().take(25);
writefln(
"-- str beg --\n%s\n-- str end --",
std::string{fr2.iter_begin(), fr2.iter_end()}
);
2016-01-31 23:19:23 +01:00
test.seek(0);
writeln("\n## BY LINE READ ##\n");
for (auto const &line: test.iter_lines()) {
writeln("got line: ", line);
}
test.close();
writeln("\n## FILE SORT ##\n");
wtest.open("test.txt", stream_mode::WRITE);
smpl = "foo\n"
"bar\n"
"baz\n"
"test\n"
"this\n"
"will\n"
"be\n"
"in\n"
"order\n";
copy(iter(smpl), wtest.iter());
wtest.close();
test.open("test.txt");
auto lns = test.iter_lines();
std::vector<std::string> x{lns.iter_begin(), lns.iter_end()};
writeln("before sort: ", x);
sort(iter(x));
writeln("after sort: ", x);
2016-01-31 23:19:23 +01:00
return 0;
2016-02-07 22:17:15 +01:00
}