Advertisement
homer512

CSV cpp

Nov 2nd, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3. #include <iostream>
  4.  
  5.  
  6. namespace {
  7.  
  8.   void replace_col(const char* inpath, const char* outpath, const char* label,
  9.                    const char* replacement)
  10.   {
  11.     std::ifstream infile(inpath);
  12.     if(! infile.good())
  13.       throw std::ios::failure("Cannot open input");
  14.     infile.exceptions(std::ios::badbit);
  15.     std::ofstream outfile(outpath);
  16.     if(! outfile.good())
  17.       throw std::ios::failure("Cannot create output");
  18.     outfile.exceptions(std::ios::badbit | std::ios::failbit);
  19.     std::string buf;
  20.     if(! std::getline(infile, buf))
  21.       return; // empty file
  22.     // Handle header. Look for column index
  23.     int replacecol = 0;
  24.     bool found;
  25.     // we stop when we haven't found a separator in the last iteration
  26.     for(std::size_t offset = 0, cursep = 0; cursep != std::string::npos;
  27.         ++replacecol, offset = cursep + 1) {
  28.       cursep = buf.find(',', offset);
  29.       if((found = ! buf.compare(offset, cursep - offset, label)))
  30.         break;
  31.     }
  32.     if(! found)
  33.       throw std::ios::failure("Column not found");
  34.     outfile << buf << '\n'; // save header unchanged
  35.     while(std::getline(infile, buf)) {
  36.       std::size_t offset, cursep;
  37.       int curcol;
  38.       for(offset = 0, cursep = 0, curcol = 0; cursep != std::string::npos;
  39.           ++curcol, offset = cursep + 1) {
  40.         cursep = buf.find(',', offset);
  41.         if(offset) // add separator to previous column
  42.           outfile << ',';
  43.         /*
  44.          * one loop before the replacement and one after it would be more
  45.          * efficient but let's keep it simple
  46.          */
  47.         if(curcol == replacecol)
  48.           outfile << replacement;
  49.         else
  50.           outfile << buf.substr(offset, cursep - offset);
  51.       }
  52.       outfile << '\n';
  53.     }
  54.     // don't rely on dtor so that we can catch IO errors
  55.     outfile.close();
  56.   }
  57. }
  58.  
  59. int main(int argc, char** argv)
  60. {
  61.   if(argc != 5) {
  62.     std::cerr << "Usage: " << argv[0]
  63.               << " INPUT.csv COLUMN REPLACEMENT OUTPUT.csv\n";
  64.     return 1;
  65.   }
  66.   replace_col(argv[1], argv[4], argv[2], argv[3]);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement