CTTL on
SourceForge |
Download
Latest |
Documentation
Index |
Library
News |
CVS
Repository |
Other
Links |
This utility converts input text file to an array of string literals.
// sample code: text2array.cpp // converts text file to array of string literals. //#define NDEBUG // define before assert.h to stop assertions from being compiled //#define CTTL_TRACE_EVERYTHING //#define CTTL_TRACE_RULES //#define CTTL_TEXT_ARRAY_INSERT_LINE_NUMBERS #include <iostream> #include "cttl/cttl.h" #include "utils/itos.h" #include "utils/fileio.h" using namespace cttl; struct text2array { static size_t match_lines( edge<>& edge_ ) { return ( +quote( true, CTTL_STATIC_RULE( text2array::event_line ) + *CTTL_STATIC_RULE( text2array::find_escape ), symbol( '\n' ) ) ).match( edge_ ); } static size_t event_line( edge<>& edge_ ) { #ifdef CTTL_TEXT_ARRAY_INSERT_LINE_NUMBERS static size_t line_count = 0; edge_.first.insert_go( "/*" ); edge_.first.insert_go( itos( line_count++ ) ); edge_.first.insert_go( "*/" ); #endif //CTTL_TEXT_ARRAY_INSERT_LINE_NUMBERS edge_.first.insert_go( "\t\"" ); edge_.second.insert_stay( "\"," ); return edge_.first.offset(); } static size_t find_escape( edge<>& edge_ ) { return ( ( symbol( '\\' ) | symbol( '\"' ) | symbol( '\'' ) | symbol( '\t' ) ) & CTTL_STATIC_RULE( text2array::event_escape_char ) ).find( edge_ ); } static size_t event_escape_char( edge<>& edge_ ) { if ( edge_.first[ 0 ] == '\t' ) edge_.text( "\\t" ); else edge_.first.insert_go( "\\" ); return edge_.second.offset(); } static bool parse( edge<>& universe_ ) { match_lines( universe_ ); if ( universe_.length() ) { ( CTTL_STATIC_RULE( text2array::event_line ) + *CTTL_STATIC_RULE( text2array::find_escape ) ).match( universe_ ); } return true; } }; int main(int argc, char* argv[]) { if ( argc == 1 ) { std::cout << "usage: specify input file to convert to array of string literals" << std::endl ; return 1; } input<> inp; file2string( argv[ 1 ], inp.container().text() ); assert( inp.length() ); edge<> universe( new_edge< std::string >( inp ) ); if ( text2array::parse( universe ) ) { std::cout << "extern const char* char_array[] = {" << std::endl ; std::cout << inp.text(); std::cout << std::endl << "\tNULL" << std::endl << "};\t// char_array" << std::endl ; return 0; } std::cout << "*** parser failed ***" << std::endl; return 1; }
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.