Commit 880ccebecf50026f70b49e6b9147304904ba7c40

Authored by Jordi Inglada
1 parent ed7ca4df
Exists in master

ENH: count_columns

Showing 1 changed file with 21 additions and 0 deletions   Show diff stats
include/cbutils.h
... ... @@ -15,8 +15,11 @@
15 15 #define __CBUTILS_H
16 16 #include <algorithm>
17 17 #include <boost/algorithm/string.hpp>
  18 +#include <cstddef>
18 19 #include <fstream>
  20 +#include <stdexcept>
19 21 #include <string>
  22 +#include <sstream>
20 23 #include <vector>
21 24 namespace cbutils
22 25 {
... ... @@ -49,6 +52,24 @@ std::vector&lt;std::string&gt; readlines(const std::string&amp; fname)
49 52 }
50 53 return lines;
51 54 }
  55 +//Count the number of columns of a CSV file
  56 +std::size_t count_columns(const std::string& fname,
  57 + const char* separators = "\t ")
  58 +{
  59 + std::ifstream ifile(fname);
  60 + if (ifile.is_open())
  61 + {
  62 + std::string line{};
  63 + std::getline(ifile,line);
  64 + return string::split(line, separators).size();
  65 + }
  66 + else
  67 + {
  68 + std::stringstream errmessage{"Could not open "+fname};
  69 + throw std::runtime_error(errmessage.str());
  70 + }
  71 + return 0;
  72 +}
52 73 }//end ns file
53 74 // ----------------- Sequence manipulation -------------------------------------
54 75 namespace seq
... ...