File: ReadWriteFile.cpp

package info (click to toggle)
librepfunc 1.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 424 kB
  • sloc: cpp: 1,601; makefile: 270
file content (53 lines) | stat: -rw-r--r-- 1,415 bytes parent folder | download
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
/*******************************************************************************
 * librepfunc - a collection of common functions, classes and tools.
 * See the README file for copyright information and how to reach the author.
 ******************************************************************************/
#include <sstream>   // std::stringstream
#include <fstream>   // std::ifstream
#include <repfunc.h>

std::stringstream ReadFileToStream(std::string aFileName) {
  std::stringstream ss;
  std::ifstream is(aFileName.c_str());
  if (is) {
     ss << is.rdbuf();
     is.close();
     }
  return ss; 
}

bool WriteStreamToFile(std::string aFileName, std::stringstream& ss) {
  std::ofstream os(aFileName.c_str());
  if (os.fail())
     return false;

  os << ss.rdbuf();
  bool result = os.good();
  os.close();
  return result;
}

std::vector<std::string> ReadFile(std::string aFileName, bool empty) {
  std::stringstream ss = ReadFileToStream(aFileName);
  std::string s;
  std::vector<std::string> result;

  while(std::getline(ss, s)) {
     if (not empty and s.empty())
        continue;
     result.push_back(s);
     }
  return result;
}

bool WriteFile(std::string aFileName, std::vector<std::string>& lines) {
  std::ofstream os(aFileName.c_str());
  if (os.fail())
     return false;

  for(const auto& s:lines)
     os << s << std::endl;
  bool result = os.good();
  os.close();
  return result;
}