MadHatter Solutions
Snippets - C++  
New Stuff - Last Update (Tuesday, July 01, 2003)

   Contributing   Authors

The MadHatter 


  Download the complete 
  database file  Snippets.zip
  This file may be  veiwed 
  with the Database program 
  that can be found from the 
  Dowloads page. 


  > Home
  > Downloads
        • FCopy
  > Snippets
  > Favorite Links
  > Tips



  Encrypt ()
  Replace ()
  Get IP Address
  Shorten_File_Name ();
  FileCopy ();
  Rand_Strng_Generator ();
A simple encryption algorithm.

The key is a randomly generated char string or any
text string such as the bill of writes or last weeks
horoscope. This function will encrypt a string using
the key passed to the function. The Mode must be selected
on the function call.

char Key [] = "98475p9bvehlwekytlwv8woi8e";
char *string;
string = new char [20];
strcpy (string, "Encrypt this string");
Encrypt (string, Key, ENCRYPT)
string now = ^'w*/a.bkNR`wY`l^[_

int Encrypt (char *string, char *Key, int mode)
{
   // This algorithm stays within the keyboard character
   // environment.

   // GLOBALS
   // char key [100000]; // this must be loaded or initialised with the key
   // int key_length;
   // enum {ENCRYPT,DECRYPT};

   char *s = new char[1000];
   int x;
   int y;
   int z;
   int len_string;
   int char_value;
   int keycount = 0;
   key_length = strlen (key);

   if (mode == ENCRYPT)
   {
      len_string = strlen (string);

      for (x = 0; x < len_string; x++)
      {
         if (string [x] == 0x9)
            s [x] = 0x9;
         else
         {
            z = (int) string [x] + ((int) Key [keycount] - 32);
            if (z <= 126)
               s [x] = (char) z;
            else
            {
               z = z - 95;
               s [x] = (char) (z);
            }

            keycount++;
            if (keycount == key_length)
               keycount = 0;
         }
      }
      s [x] = NULL;
      strcpy (string, s);
   }

   else if (mode == DECRYPT)
   {
      len_string = strlen (string);

      for (x = 0; x < len_string; x++)
      {
         if (string [x] == 0x9)
            s [x] = 0x9;
         else
         {
            z = (int) string [x] - ((int) Key [keycount] - 32);
            if (z >= 32)
               s [x] = (char) z;
            else
            {
               z = z + 95;
               s [x] = (char) z;
            }

            keycount++;
            if (keycount == key_length)
               keycount = 0;
         }
      }
      s [x] = NULL;
      strcpy (string, s);
   }

   delete s;

   return 0;
}

Submitted by the "MadHatter" 

Go Back To the List 


Use this function to search a string for every instance
of a selected token string and replace it with a selected string.

buff = initial string;
replace(buff, token, filler);
buff now = new string;

void replace(char *str, char *token, char *filler)
{
   int x;
   int y;
   int z;

   char buff1 [256];
   char buff2 [512];

   for (z = 0; z < 512; z++)
      buff2 [z] = NULL;

   x = strlen (str);
   y = strlen (token);

   for (int xx = 0; xx < x; xx++)
   {
      for (z = 0; z < 256; z++)
         buff1 [z] = NULL;

      int yy;

      for (yy = 0; yy < y; yy++)
         buff1 [yy] = str [xx + yy];

         buff1 [yy] = NULL;

      if (!strcmp (buff1, token))
      {
         strcat (buff2, filler);
         xx = xx + y - 1;
      }
      else
      {
         z = strlen (buff2);
         buff2 [z] = str [xx];
         buff2 [z + 1] = NULL;
      }
   }

   strcpy (str, buff2);
}

Submitted by the "MadHatter" 

Go Back To the List 


This code will get the Ip addresses from the
computer it is run on. It will load a list box
with the IP addresess found.


#include <stdio.h>
#include <Winsock.h>

TStringList *IPAddress;

__fastcall TConfigureForm::TConfigureForm(TComponent* Owner)
    : TForm(Owner)
{
    Edit1->Text = "User";
    IPAddress = new TStringList;
}

void __fastcall TConfigureForm::FormCreate(TObject *Sender)
{
     // load a list box with the ip addresses;
    WORD wVersionRequested;
    WSADATA wsaData;
    char name[255];
    PHOSTENT hostinfo;
    wVersionRequested = MAKEWORD( 1, 1 );
    AnsiString ip;
    AnsiString Str1;
    FILE *file;

    char *buff = new char [16];

    if ((file = fopen ("chatterIP.log", "r")) != NULL)
    {
        bool done = false;
        while (!done)
        {
            fgets(buff, 16, file);
            int x = strlen (buff);
            buff [x - 1] = NULL;
            if (IPAddress->IndexOf (buff) == -1)
                IPAddress->Add (buff);
            if (feof(file))
                done = true;
        };

        fclose (file);
    }

    if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
        if( gethostname ( name, sizeof(name)) == 0)
        {
            if((hostinfo = gethostbyname(name)) != NULL)
            {
                Edit3->Text = name;
                ComboBox1->Clear ();
                int nCount = 0;
                while(hostinfo->h_addr_list[nCount])
                {
                    ip = inet_ntoa(*(struct in_addr *)hostinfo->h_addr_list[nCount]);
                    ComboBox1->Items->Add (ip);
                    nCount++;

                    if (IPAddress->IndexOf (ip) == -1)
                        if ((file = fopen("chatterIP.log", "a")) != NULL)
                        {
                            fprintf (file, "%s\n", ip.c_str ());
                            fclose (file);
                        }

                    ComboBox1->ItemIndex = 0;
                }
            }
       }
}

Submitted by the "MadHatter" 

Go Back To the List 


 The function below will shorten a long file path to allow it   
to fit into a shorter label or text string.  The resulting text   
string should be recognized as a file path abbreviation. 

void Shorten_File_Name (char *string, int x) 
 // x = the target path length.  If the extracted file name 
 // is large enough it will possibly exceed the target length. 
 // Windows filenames can get quite large and you may want to 
 // allow the ability to shorten that if exceeds a certain length. 
 // The function will handle this but the results as coded may 
 // not fit your preferences. 

 // input - C:\Program Files\Borland\CBuilder5\Examples\Apps\Cursors\readme.txt 
 // output - C:\Progr...\readme.txt 

 { 
     int length = strlen (string); 
     int a; 
     int b; 
 
     if (length > x) 
     { 
         char *buff1 = new char [60]; // filename max length 
         char *buff2 = new char [256]; 

         strcpy (buff1, ExtractFileName(string).c_str ()); 

         a = x - strlen (buff1); 

         if (a > 3)   // if there is enough room. 
         { 
             for (b = 0; b < (a - 2); b++) 
                 buff2 [b] = string [b]; 

             buff2[b] = NULL; 
         } 
         else   // this just appends the file name to the drive name 
                  // with the "..." in the middle. 
         { 
             for (b = 0; b < 3; b++) 
                 buff2 [b] = string [b]; 

             buff2[b] = NULL; 
         } 

         strcat (buff2, "...\\"); 
         strcat (buff2, buff1); 

         strcpy (string, buff2); 
         delete buff1; 
         delete buff2; 
     } 
 } 

Submitted by the "MadHatter" 

Go Back To the List 


My very own copy function 

#include <stdio.h> 
#include <io.h> 

int FileCopy (char *sourcefile, char *targetfile) 

    char *buffer1 = new char [500]; 
    char *buffer2 = new char [50]; 
    int SourceFileHandle; 
    int TargetFileHandle; 
    int filelength1 = -1; 
    int filelength2 = -1; 
    char *FileBuffer; 
    FILE *stream; 
    std::ftime ft; 

    try 
    { 
        // get the file date to set the date of the copied file. 
        if ((stream = fopen(sourcefile, "r")) != NULL) 
        { 
            getftime(fileno(stream), &ft); 
            fclose(stream); 
        } 

        SourceFileHandle = FileOpen (sourcefile, fmOpenRead|fmShareDenyNone); 

        if (SourceFileHandle != -1) 
        { 
            filelength1 = FileSeek(SourceFileHandle, 0, 2); 
            FileSeek(SourceFileHandle, 0, 0); 
            FileBuffer = new char[filelength1 + 1]; 
            FileRead(SourceFileHandle, FileBuffer, filelength1); 
            FileClose(SourceFileHandle); 

            TargetFileHandle = FileCreate(targetfile); 
            filelength2 = FileWrite(TargetFileHandle, FileBuffer, filelength1); 
            FileClose(TargetFileHandle); 

            if (filelength2 >= 0) 
            { 
                // set the file date to the original/ 
                if ((stream = fopen(targetfile, "r+")) != NULL) 
                { 
                    setftime(fileno(stream), &ft); 
                fclose(stream); 
                } 
            } 
        } 

        delete FileBuffer; 
    } 
    catch(...) 
    { 
    } 

    delete buffer1; 
    delete buffer2; 

    if (filelength1 != filelength2) 
        filelength2 = -1; 

    return  filelength2; 

Submitted by the "MadHatter" 

Go Back To the List 


Random String Generator

This function will generate a string of x length
filled with randomly selected characters

#include <stdlib.h>

void Rand_Strng_Generator (void)
{
   int i = 0;
   int x;
   bool done = false;
   char buff1 [46];

   randomize();

   while (!done)
   {
      x = random (128);

      if (isalnum ((char) x))
      {
         buff1 [i] = (char) x;

         i++;
      }

      if (i == 45)
         done = true;
   }

   buff1 [i] = NULL;
)

Submitted by the "MadHatter" 

Go Back To the List


The code displayed is intended for reference and example only.  There is
no intention to guarantee any code as fit for any purpose.  The purpose of this
page is to merely make available some code in our personal collections.

If you would like to submit a snippet please send it to The MadHatter.
Please don't send  source code greater than 100 lines. Anything larger
may be considered but this site is not intended for full programs or extremely
large functions.  The code displayed will be edited for content.  Please keep
the comments in your code clean.  I will list your name, email or webpage link
as a contributing author if you wish.  Your contribution will be anonymous
unless otherwise requested.

And I will not accept code that is written like a brick.  I can not spend to
much time properly formatting your submission.  Please add any #include
statements that the function is dependant upon.

I intend to make the code available as a database file that can be viewed with the
database program found on the downloads page.

  Top