[icoSystem.png]Sitemap
[icoDocs.png]Documents
[icoFolderApps.png]Program files
[icoFolderWin.png]Windows
[icoDocs.png] Documents[icoFolderBorland.png] Borland files[icoFile.png] Some c++ code
[icoFile.png]
 Some c++ code (24oct2010)
A function to calculate the hash of a string I used to check files modifications:
 unt_Hashing.cpp
//#include <vcl.h> #pragma hdrstop #include "unt_Hashing.h" #pragma package(smart_init) //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby (but modified by me) // Note - This code makes a few assumptions about how your machine behaves: // .We can read a 4-byte value from any address without crashing // And it has a few limitations: // .It will not work incrementally. // .It will not produce the same results on little-endian and big-endian machines. unsigned int MurmurHash2 ( const void * key, int len, unsigned int seed ) { // 'm' and 'r' are mixing constants generated offline. const unsigned int m = 0x12345678; const int r = 51; const int sz = sizeof(unsigned int); // [bytes] // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char * data = (const unsigned char *)key; while(len >= sz) { unsigned int k = *(unsigned int *)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += sz; len -= sz; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << (4*sz); case 2: h ^= data[1] << (2*sz); case 1: h ^= data[0]; h *= m; } // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> (4*sz - 3); h *= m; h ^= h >> (4*sz - 1); return h; }
An example of class derivation from standard exception:
 myexception.cpp
/////////////////////////////////////////////////////////////////////////// // A custom exception type class Esomethingbad : public std::exception { public: Esomethingbad() throw() {;} virtual ~Esomethingbad() throw() {;} virtual const char* what() const throw() {return "Something wrong happened";} }; // end 'Esomethingbad'
An example of using a fstream iterator:
 fstream iterator.cpp
#include <iostream> // 'cin', 'cout' #include <fstream> // 'fstream' void findsomething(std::string in) { const std::string tofind("something"); if(match==in) std::cout << "Found " << tofind << std::endl; } try{ std::ifstream f; f.exceptions ( std::ios::failbit | std::ios::badbit ); f.open("file.txt"); std::istream_iterator<std::string> start(f), finish; std::for_each(start, finish, findsomething); } catch(std::exception& e) {std::cout << "Error: " << e.what() << std::endl;}
A small program I wrote to replaces the occurrences of a string in a file. Is a good example of using fstream in binary mode.
 replace string.cpp
/* Name : ReplaceString.cpp Author : mat Version : 2010-05-10 Copyright : Modify freely Description : Replace a string in a file Dependencies: */ #include <iostream> // 'cin', 'cout' #include <fstream> // 'fstream' #include <stdexcept> // 'runtime_error' #include <string.h> // 'strlen' //#include <memory> // 'auto_ptr' // File scope decls enum MAIN_ERRORS {RET_OK=0, RET_ERR=-1}; typedef std::ios::char_type typ_char; typedef std::streamsize typ_pos; //--------------------------------------------------------------------------- int main(int argc, char *argv[]) { try{ // . (1) Arguments //for(int i=1; i<argc; ++i) std::cout << i << ") " << argv[i] << std::endl; if(argc!=4) throw std::runtime_error(":> ReplaceString \"file.txt\" \"oldstring\" \"newstring\""); std::string ifilepath = argv[1]; typ_char *oldstr = argv[2]; typ_pos oldstr_len = strlen(oldstr); typ_char *newstr = argv[3]; typ_pos newstr_len = strlen(newstr); // . (2) Buffer the input file std::cout << "Buffering \'" << ifilepath << "\'" << std::endl; typ_char *buf = 0; typ_pos buf_siz = 0; std::fstream ifile; ifile.exceptions ( std::ios::failbit | std::ios::badbit ); ifile.open(ifilepath.c_str(), std::ios::in|std::ios::binary|std::ios::ate); buf_siz = ifile.tellg(); buf = new typ_char[buf_siz]; ifile.seekg (0, std::ios::beg); ifile.read(buf, buf_siz); ifile.close(); // . (3) Prepare destination std::string ofilepath = ifilepath; std::cout << "Writing to \'" << ofilepath << "\'" << std::endl; std::fstream ofile; ofile.exceptions ( std::ios::failbit | std::ios::badbit ); ofile.open(ofilepath.c_str(), std::ios::out|std::ios::binary); // . (4) Scan operation std::cout << "Scanning ..." << std::endl; std::string matching = ""; typ_pos i=0; typ_pos m=0; while ( i < buf_siz ) { if ( buf[i] == oldstr[m] ) { if ( ++m >= oldstr_len ) { std::cout << ".Replacing \'" << oldstr << "\' with \'" << newstr << "\' at char " << i << std::endl; ofile.write(newstr,newstr_len); m = 0; } } else { if(m>0) { ofile.write(oldstr,m); m=0; } ofile.write(&(buf[i]),1); } ++i; } std::cout << i << " characters processed" << std::endl; // . (5) Finally if(buf) delete[] buf; ofile.close(); std::cout << "...Done" << std::endl; return RET_OK; } catch( std::exception& e) { std::cout << "Error: " << e.what() << std::endl; } // Should probably do some maintenance here, but I'm exiting anyway return RET_ERR; } // end 'main'
A pair of functions to compute the rational approximation of a real number given the maximum numerator/denominator and error.
 Rational approximation.cpp
/* Name : Rational approximation.cpp Author : mat Version : 2011-09-26 Copyright : Use and modify freely Description : Rational approximation of a real number given maximum numerator - denominator and maximum error Dependencies: */ #include <cmath> // std::fabs #include <limits> const double x_max = static_cast<double>(std::numeric_limits<int>::max()); const double eps = std::numeric_limits<double>::min(); //--------------------------------------------------------------------------- // Find the approssimating rational using 'continuous fraction' method void RationalApprox_ContFrac(double x, const int M, const double& e) { bool neg = x<0; x = std::fabs(x); int ak, Nk=1, Dk=0, Nk_1=0, Dk_1=1, Nk_2, Dk_2; double xki, xkf=x, ek=2*x, ek_1; do { // . Separate integer and fractional parts xkf = std::modf(xkf, &xki); if(xki<=x_max) ak = xki; // Continuous fraction expansion term else throw xki; // too big // .Calculate convergents Nk_2 = Nk_1; Dk_2 = Dk_1; Nk_1 = Nk; Dk_1 = Dk; Nk = ak*Nk_1 + Nk_2; Dk = ak*Dk_1 + Dk_2; // If outside maximum, roll back and stop if(Nk>M || Dk>M) { Nk = Nk_1; Dk = Dk_1; break; } // . Check approximation ek_1 = ek; ek = std::fabs(x-(double(Nk)/double(Dk))); // If error isn't decreasing, roll back and stop if (ek >= ek_1) { Nk = Nk_1; Dk = Dk_1; break; } // . Next term of continuous fraction expansion if(xkf<=eps) break; // TODO: truncate in a better way xkf = 1/xkf; } while (ek > e); // . Finally, the result int N = neg ? -Nk : Nk; int D = Dk; } // end 'RationalApprox_ContFrac' //--------------------------------------------------------------------------- // Find the approssimating rational using 'Farey sequence' method (not tested) void RationalApprox_Farey(double x, const int M, const double& e) { // . Prepare bool neg = x<0; x = std::fabs(x); if(x>x_max) throw x; // x too big int N1 = static_cast<int>(x); int N2 = N1+1; int D1=1, D2=1; int N3=N1, D3=D1; double v; // . Iterative approximation do { int Ntmp = N1 + N2; int Dtmp = D1 + D2; if(Ntmp>M || Dtmp>M) break; else {N3=Ntmp; D3=Dtmp;} v = double(N3)/double(D3); if(std::fabs(x-v)<e) break; else {if(v<x){N1=N3; D1=D3;} else{N2=N3; D2=D3;}} } while(true); // . Finally, the result int N = neg ? -N3 : N3; int D = D3; } // end 'RationalApprox_Farey'