Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Tvrtko remind-nix.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

C++ code to HTML

generate html colored file from a source file

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
using namespace std;

#include <boost/regex.hpp>

const char * expressions =
	// comments
	"(//[^\\n]*|/\\*.*?\\*/)|"
	// precompilers
	"(^[[:blank:]]*#[^\\n]*)|"
	// string literals
	"(\"(?:[^\\\\\"]|\\\\.)*\"|'(?:[^\\\\']|\\\\.)*')|"
	// floating point literal
	"(\\<[[:digit:]]+\\.[[:digit:]]+)|"
	//  integer literal
	"(\\<[[:digit:]]+\\>)|"
	// boolean literal
	"((?:\\<true\\>)|(?:\\<false\\>))|"
	// keywords
	"\\<(__asm|__cdecl|__declspec|__export|__far16|__fastcall|__fortran|__import"
	"|__pascal|__rtti|__stdcall|_asm|_cdecl|__except|_export|_far16|_fastcall"
	"|__finally|_fortran|_import|_pascal|_stdcall|__thread|__try|asm|auto|bool"
	"|break|case|catch|cdecl|char|class|const|const_cast|continue|default|delete"
	"|do|double|dynamic_cast|else|enum|explicit|extern|false|float|for|friend|goto"
	"|if|inline|int|long|mutable|namespace|new|operator|pascal|private|protected"
	"|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_cast"
	"|struct|switch|template|this|throw|true|try|typedef|typeid|typename|union|unsigned"
	"|using|virtual|void|volatile|wchar_t|while)\\>";

const char * format = 
	"(?1<font color = \"#999999\"><i>$&</i></font>)"
	"(?2<font color = \"#000099\">$&</font>)"
	"(?3<font color = \"#009900\">$&</font>)"
	"(?4<font color = \"#996600\">$&</font>)"
	"(?5<font color = \"#999900\">$&</font>)"
	"(?6<font color = \"#660000\"><b>$&</b></font>)"
	"(?7<font color = \"#336699\"><b>$&</b></font>)";

string help = 
	"Usage:"
	"\n\nccode2html <input file> <output file>"
	"\n\nIf output filename is omitted its name it will be <input file>.html";
string code_tag_start = "<PRE>";
string code_tag_end = "</PRE>";

void ccode2html (string input, string output);
string test();

extern const char* pre_expression = "(<)|(>)|(&)|\\r";
extern const char* pre_format = "(?1\\&lt;)(?2\\&gt;)(?3&amp;)";

int main (int argc, char *argv[])
{
	string input_file;
	string output_file;
	if (argc > 3 || argc==1) {
		cout << help;
		exit(0);
	}
	else if (argc==2) {
		input_file=argv[1];
		output_file=input_file+".html";
		ccode2html (input_file, output_file);
	} else {
		input_file=argv[1];
		output_file=argv[2];
		ccode2html (input_file, output_file);
	}
	return 0;
}

// ccode2html method

void ccode2html (string input, string output)
{
	try {
		boost::regex e1, e2;
		e2.assign(pre_expression);
		e1.assign(expressions);
		fstream in (input.c_str(), fstream::in);
		fstream out (output.c_str(), fstream::out);
		out << "<pre>";
		string ins;
		char c;
		while (in.get (c)) {
			ins.append (1, c);
		}
		ostringstream t(std::ios::out | std::ios::binary);
		ostream_iterator<char, char> io(t);
		boost::regex_replace(io, ins.begin(), ins.end(), e2, pre_format, 
				boost::match_default | boost::format_all);
		string s(t.str());
		std::ostream_iterator<char, char> o(out);
		boost::regex_replace(o, s.begin(), s.end(), e1, format,
				boost::match_default | boost::format_all);
		out << "</pre>";
		cout << s;
		cout << input << endl;
		cout << output << endl;
		test();
	} catch (char * exc) {
		cout << "errors:" << endl;
		cout << exc << endl;
	}
}

Put mounted drives list into Glist

Function that gets list of mounted drives from '/etc/fstab' and '/etc/mtab' files and puts data in the GList object (from GLib library) that can be further used in GTK.

#include <glib.h>
#include <mntent.h>
#include <string.h>

GList * g_get_drives_list(GList * g) {
	FILE *fstab = NULL;
	struct mntent *part = NULL;
	gchar *mntp = NULL;
	
	if ((fstab = setmntent( "/etc/fstab", "r" )) != NULL) {
		while ((part = getmntent(fstab))  != NULL) {
			if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0 
																					&& (strcmp(part->mnt_type, "swap")) != 0) {
				mntp = g_strdup(part->mnt_dir);
				g=g_list_append(g, mntp);
			}
		}
		endmntent(fstab);
	}
	
	if ((fstab = setmntent( "/etc/mtab", "r")) != NULL) {
		while ((part = getmntent(fstab)) != NULL) {
			if (part->mnt_type != NULL) {
				if((strcmp(part->mnt_type, "proc")) != 0 && (strcmp(part->mnt_type, "devpts")) != 0
						&& (strcmp(part->mnt_type, "swap")) != 0 && (strcmp(part->mnt_type, "sysfs")) != 0
						&& (strcmp(part->mnt_type, "tmpfs")) != 0 && (strcmp(part->mnt_type, "fuseblk")) != 0
						&& (strcmp(part->mnt_type, "securityfs")) != 0) {
					if((g_list_find_custom(g, part->mnt_dir, (GCompareFunc)strcmp)) == 0) {
						mntp=g_strdup(part->mnt_dir);
						g=g_list_append(g, mntp);
					}
				}
			}
		}
		endmntent(fstab);
	}
	return g;
}

Code 2 HTML

This is a simple python program that reads a file (code), and replaces line breaks and spaces with appropriate tag and entity.

import sys

line_break='<br>'
nb_space='&#160;'

def toHtml(f,out):
    try:
        fo=open(out,'w')
    except IOError:
        print 'output file error!'
    else:
        for line in f:
            line=line.replace('\t',nb_space*8)
            line=line.replace(' ',nb_space)
            line=line.replace('\n',line_break)
            fo.write(line)
        fo.close()
        

if len(sys.argv) == 1:
    print("at least one argument / input filename / required")
    sys.exit()
if len(sys.argv) > 3:
    print"too many arguments"
    sys.exit()       
try:
    f=open(sys.argv[1],'r')
except IOError:
    print 'cannot open file ', sys.argv[1]
else:
    if len(sys.argv) == 2:
        out=f.name + '.html'
    else:
        out=sys.argv[2]
    toHtml(f, out)
    f.close()

decompressing various archive types

// decompressing various archive types with this python script
// usage unpack <archive filename>

#!/usr/bin/env python
#
# simple python script for extracting mostly used types of archives
# this script extracts .tar, .tar.gz, .tar.bz2, .gz and .zip archives 
#

import sys	# required for fetching command line arguments 
import os	# required for calling commands for archive extracting

def unpack(s):									# this is definition of depack
	if (s.find('.tar.gz') != -1):				#	function. It takes string
		os.system("tar -xvvzf " + filename)		#   filename as argument.
	elif (s.find('.tar.bz2') != -1):			#	functon than calls 
		os.system("tar -xvvjf " + filename)		#   appropriate command according
	elif (s.find('.tar') != -1):				# 	to file extension
		os.system("tar -xvvf " + filename)
	elif (s.find('.gz') != -1):
		os.system("gunzip" + filename)			
	elif (s.find('.zip') != -1):		
		os.system("unzip " + filename)
	else: print "Wrong archive or filename"		# other types not supported

try:											# this is main program
	filename = sys.argv[1]						# first argument right after
	unpack(filename)							#	'unpack' command goes in the
except IndexError:								#	filename string
	print "Filename is invalid!"				#	than the depack function is called

# try-except block is used for handling IndexError exception if no argument is passed
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS