From f6123ac9f1044e4e7ef03145ee5ccda5fd3339e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Fri, 18 Oct 2019 00:00:01 +0000 Subject: [PATCH] c++: file_read_write --- README.adoc | 2 ++ userland/cpp/file_write_read.cpp | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 userland/cpp/file_write_read.cpp diff --git a/README.adoc b/README.adoc index 1d3af70..51e7864 100644 --- a/README.adoc +++ b/README.adoc @@ -13540,6 +13540,8 @@ Programs under link:userland/cpp/[] are examples of https://en.wikipedia.org/wik ** link:userland/cpp/template.cpp[]: basic example ** link:userland/cpp/template_class_with_static_member.cpp[]: https://stackoverflow.com/questions/3229883/static-member-initialization-in-a-class-template ** link:userland/cpp/if_constexpr.cpp[]: C++17 `if constexpr` +* fstream +** link:userland/cpp/file_write_read.cpp[] [[cpp-multithreading]] ==== C++ multithreading diff --git a/userland/cpp/file_write_read.cpp b/userland/cpp/file_write_read.cpp new file mode 100644 index 0000000..b67733e --- /dev/null +++ b/userland/cpp/file_write_read.cpp @@ -0,0 +1,46 @@ +/* https://cirosantilli.com/linux-kernel-module-cheat#cpp */ + +#include + +#include +#include +#include + +// https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c +// https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring +std::string read_file(const std::string& path) { + std::ifstream ifs(path); + assert(ifs.is_open()); + std::stringstream sstr; + sstr << ifs.rdbuf(); + return sstr.str(); +} + +int main(void) { + std::string path = LKMC_TMP_FILE; + std::string data = "asdf\nqwer\n"; + + // Write entire string to file at once. + { + std::ofstream ofs(path); + assert(ofs.is_open()); + ofs << data; + ofs.close(); + } + + // Read entire file into string. + std::string read_output = read_file(path); + assert(read_output == data); + + // Append to a file. + { + std::string append_data = "zxcv\n"; + std::ofstream ofs(path, std::ios::app); + assert(ofs.is_open()); + ofs << append_data; + ofs.close(); + assert(read_file(path) == data + append_data); + } + + return EXIT_SUCCESS; +}