libutil++  1.9.3
 All Classes Functions Variables
GZCSVPathWriter.cpp
1 /*
2 ** libutil++
3 ** $Id: GZCSVPathWriter.cpp 1653 2016-02-28 19:54:59Z sella $
4 ** Copyright (c) 2011-2016 Digital Genesis, LLC. All Rights Reserved.
5 ** Released under the LGPL Version 2.1 License.
6 ** http://www.digitalgenesis.com
7 */
8 
9 static const char rcsid[] __attribute__((used)) = "$Id: GZCSVPathWriter.cpp 1653 2016-02-28 19:54:59Z sella $";
10 
11 #include "GZCSVPathWriter.h"
12 #include "GZCSVFileWriter.h"
13 
14 #include <fcntl.h>
15 #include <dirent.h>
16 
17 using namespace sella::file;
18 
19 const char * GZCSVPathWriter::FileSuffix = ".csv.gz";
20 
30 GZCSVPathWriter::GZCSVPathWriter(const std::string & path, char delimiter, char seperator) THROWS(IOException) :
31  path(path),
32 
33  delimiter(delimiter),
34  seperator(seperator),
35 
36  sequence(::time(NULL) << 16)
37 {
38  /* Ensure the supplied path is valid. */
39  DIR * directory = ::opendir(this->path.c_str());
40 
41  if (directory == NULL) {
42  THROW(IOException, "failed to open directory '%s' for writing", this->path.c_str());
43  }
44  ::closedir(directory);
45 
46  /* Remove any trailing slash characters from the path. */
47  while (*(this->path.rbegin()) == '/') {
48  this->path.erase(this->path.length() - 1, 1);
49  }
50 }
51 
59 void GZCSVPathWriter::write(const std::vector<std::vector<std::string>> & data) THROWS(IOException) {
60  char file[2][4096];
61 
62  snprintf(file[0], sizeof(file[0]), "%s/%08lx.%s-incomplete", this->path.c_str(), this->sequence, GZCSVPathWriter::FileSuffix);
63  snprintf(file[1], sizeof(file[1]), "%s/%08lx.%s", this->path.c_str(), this->sequence++, GZCSVPathWriter::FileSuffix);
64 
65  GZCSVFileWriter writer(file[0], this->delimiter, this->seperator);
66 
67  for (auto iter = data.begin(); iter != data.end(); ++iter) {
68  writer.write(*iter);
69  }
70  writer.close(file[1]);
71 }
72 
73 /*
74 ** vim: noet ts=3 sw=3
75 */
void write(const std::vector< std::vector< std::string >> &data) THROWS(IOException)
A GZIP compressed CSV writer.
GZCSVPathWriter(const std::string &path, char delimiter=DefaultDelimiter, char seperator=DefaultSeperator) THROWS(IOException)
static const char * FileSuffix
The file suffix for matching files in the directory for reading.