Sinisterly
[c] CSV to XML - Printable Version

+- Sinisterly (https://sinister.li)
+-- Forum: Coding (https://sinister.li/Forum-Coding)
+--- Forum: C, C++, & Obj-C (https://sinister.li/Forum-C-C-Obj-C)
+--- Thread: [c] CSV to XML (/Thread-c-CSV-to-XML)



[c] CSV to XML - titbang - 08-11-2017

This program converts CSV files to XML files.

Requires: boost

Code:
#include <iostream> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> using namespace std; std::vector<std::string> tokens, options; string in_buffer, out_buffer, root_element, attr_element; long item_count; int read_file_to_buffer( string filename ) { char line[12]; FILE* pFile = fopen( filename.c_str(), "r" ); if( pFile != NULL ) { while( fgets( line, sizeof( line ), pFile ) ) { in_buffer.append( line ); } } else { return 1; } return 0; } int write_buffer_to_file( string filename ) { FILE* pFile = fopen( filename.c_str(), "w" ); if( pFile != NULL ) { fwrite (out_buffer.c_str(), sizeof(char), out_buffer.size(), pFile); fclose(pFile); } else { return 1; } return 0; } int chop_and_screw_it() { split(tokens, in_buffer, boost::algorithm::is_any_of(",\r\n") ); int y=0, c=0; for(vector<int>::size_type i = 0; i != tokens.size(); i++ ) { tokens[i] = boost::algorithm::replace_all_copy( tokens[i], "\"", ""); if( y == 0 ) { out_buffer.append( "<" + attr_element + " id=\"" + boost::lexical_cast<std::string>( c ) + "\">\n" + "<" + options[y] + ">" + tokens[i] + "</" + options[y] + ">\n" ); y++; c++; } else if( y > 0 && y < item_count-1) { out_buffer.append( "<" + options[y] + ">" + tokens[i] + "</" + options[y] + ">\n" ); y++; } else { out_buffer.append( "<" + options[y] + ">" + tokens[i] + "</" + options[y] + ">\n" + "</" + attr_element + ">\r\n\r\n" ); y=0; } } return 0; } int main(int argc, char* argv[]) { if( argc > 5 ) { root_element=argv[3]; attr_element=argv[4]; item_count = argc-5; for( int x = 5; x <= argc-1; x++ ) { options.push_back( argv[x] ); } } else { printf("csv2xml<: usage: <input_file> <output_file> <root_element> <attr_element> <element_names>\r\n"); return 1; } read_file_to_buffer( argv[1] ); if( !in_buffer.empty()){ chop_and_screw_it(); } else { printf("csv2xml<: unable to read file\r\n"); return 2; } if( write_buffer_to_file( argv[2] ) == 0 ) { printf("csv2xml<: saved xml file to disk\r\n"); } else { printf("csv2xml<: unable to save file\r\n"); return 3; } return 0; }