Never been to CodeSnippets 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 (or not, you can keep them private!)

Get String Properties From Entitiesss

// description of your code here

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JPAUtil {
  Statement st;
  
  public JPAUtil() throws Exception{
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }
  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}



Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Using this function you will avoid 'Undefined index' orr

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>


Windows Live

6144 users tagging and storing useful source code snippets

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>
Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Subscribe to a RSS feed of your posts

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>
Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Unlock directory (decrypt)

#!/bin/bash
log=$(find . -name *.des3)
PS3='Unlock: '
select selection in $log;do
if [ $selection ];then
desc3file=$selection
break
else
echo "Invalid selection"
fi
done
echo "Opening: " $desc3file
echo -n "Enter archive password: "
read -s password
echo -e "\nWorking"
cat $desc3file | openssl des3 -d -k $password | tar x
rm $desc3file

Archive (recursively copy) some directory

How does one make a recursive, identical copy of /source/ into /target/?

I suppose you want to do that for archiving or duplicating something and want to preserve "everything". That includes permissions, ownership, filetypes, timestamps etc. Additionally I assume, that you create /target in advance. This is not required for any of the methods, but I would have to make a case-distinction for every method depending on whether the /target-directory exists or not (but see Note 3 at the very end). Check note 2 for a remark about sparse files.

There are multiple ways to do it. On a GNU system the simplest way is:
# METHOD 1: Using GNU cp
cp -a /source/. /target/

Two remarks:
(1) If you used "/source" (or "/source/") as first argument, you would end up with /target/source/... This is usually no problem though: simply cd into target, then mv everything from ./source to . (either using mv twice, once with source/* and once with source/.* or using it only once with "shopt -s dotglob" in front). Copying one level of directories to many (like "source" in the example above) is much less annoying than copying one level to few (and e.g. ending up with all stuff under "source" besides /target instead of inside it).
So if in doubt, use a syntax that copies "one level too many".
However, it could be a problem if either "*" or ".*" expand to "very much entries" and you get an error along the lines of "argument list too long". In that case you'd need to work around the issus with a loop:
# NOTE: not a method to copy but how to clean up after copying "one level too much"
cd /target; shopt -s dotglob; for f in source/*; do mv "$f" .; done; rmdir source.

Best thing of course is, to do it right in the first place as I showed above.

(2) The -a-option to cp is a GNUism. But GNU tools are very widespread, so it's the first method I show and the preferred one if it's available because of its simplicity. Note that the often used "cp -R" does not preserve attributes: "cp -R is a broken -a" - even with -p and especially if people suggest "-r" (lower case). YOU ALMOST NEVER WANT -R or -r!

The second method is (pretty) universally available (and my personal favourite):
# METHOD 2: tar (available everywhere)
cd /source; tar cf - . | (cd /target && tar xf -)

I can't think of a system where that would not work (though it's not POSIX, since POSIX does not know tar...). Some notes as well:
(1) the cd commands could be replaced by -C option to tar, which again is a GNUism. (2) the "&&" in the extraction-subshell makes sure you don't clobber your filesystem if /target is not there.

The third (and last) method I show uses rsync. The advantage here is, that it can be "restarted from where it left" if interrupted (while cp or tar wouuld have to start from the beginning). So it may be the preferred method for large amounts of data. The disadvantage is, that rsync is far less readily available than tar or even GNU cp.
# METHOD 3: rsync (can be "re-started", mind the -H option!)
rsync -aH /source/ /target

(many pepole like to add a "-v" (--verbose) to the options, to make rsync show, what it does). The rsync "a" option is similar to the cp "a" option. They both stand for "archive" which is, what we want to do: preseve everything. For rsync however there is one notable exception: hard links. That's why we throw in the additional "H". Also note the trailing "/" on "/source/": It tells rsync to copy the contents of "/source", not "/source" itself. Omitting the trailing slash we'd end up with "/target/source/..." - not a desaster, as I noted above.

Some final notes:

(1) there sure are other ways. I can think of cpio and pax (which nobody knows but is POSIX...)
(2) If sparse files are an issue check the -S parameter for rsync/(GNU)tar or --sparse for (GNU) cp
(3) to copy "everything but some subdirectories" you need the respective exclude-options for tar/rsync. cp cannot do that.
(4) ok, I didn't want to...but: If /target does not exists (or is a file instead of a directory) the "cp" method does not change. It errors if /target exists but is not a directory and creates the directory if no /target exists. The same goes for rsync. The tar method requires a container in advance to "untar" into.

Delete specified directories with find


# only delete the specified directories

find -x -E /path/to/dir \( -type d -regex '.*/(dirname1|dirname2|dirname3)' -prune \) -ls
find -x -E /path/to/dir \( -type d -regex '.*/(dirname1|dirname2|dirname3)' -prune \) -exec /bin/rm -PRfv '{}' \;
find -x -E /path/to/dir \( -type d -regex '.*/(dirname1|dirname2|dirname3)' -prune \) -exec /bin/rm -PRfv '{}' +    # faster (Mac OS X 10.5)

find -x /path/to/dir -mindepth 1 \( -path "*/dirname1/*" -or -path "*/dirname2/*" -or -path "*/dirname1" -or -path "*/dirname2" \) -ls
find -x /path/to/dir -mindepth 1 \( -path "*/dirname1/*" -or -path "*/dirname2/*" -or -path "*/dirname1" -or -path "*/dirname2" \) -delete


# delete anything except the specified directories

find -x /path/to/dir -mindepth 1 \( ! -path "*/dirname1/*" ! -path "*/dirname2/*" \) -ls
find -x /path/to/dir -mindepth 1 \( ! -path "*/dirname1/*" ! -path "*/dirname2/*" \) -delete

Counting files


time -p /usr/bin/find -x "${HOME}" -type f -print0 | /usr/bin/tr -dc '\0' | /usr/bin/wc -c

function countfiles() { declare -i i=0; while read -d $'\0' file; do let i++; done < <(/usr/bin/find -x "${HOME}" -type f -print0); echo $i; return 0; }
time -p countfiles



Three C code snippets to count files (using recursive directory scanning).

1. A raw file counter for Mac OS X:
/*

countfiles -- count the number of regular Mac OS X files in a given directory


Note: 
- skips symbolic links and Mac-type aliases
- skips /dev directory


compile with: 

gcc -std=c99 -Wall -Wextra -pedantic -O3 -framework CoreServices -o countfiles countfiles.c


Usage:

./countfiles ~
./countfiles ~/Desktop

Compare with:
/usr/bin/find -x ~ -type f -print0 | /usr/bin/tr -dc '\0' | /usr/bin/wc -c


Note also: 
The maximum length of a name in a directory is MAXNAMLEN (cf. /usr/include/sys/dirent.h):
     #define     __DARWIN_MAXNAMLEN     255
     #define     MAXNAMLEN     __DARWIN_MAXNAMLEN


References:

- http://www.sleuthkit.org/mac-robber/desc.php   
  (directory scanner code; author: Brian Carrier; license: GNU version 2 or later, http://en.wikipedia.org/wiki/GNU_General_Public_License)

- http://my-sample-code.googlecode.com/svn/trunk/realpath/realpath.c  
  (resolves symbolic links as well as Mac-type aliases; author: MM Weiss; license: BSD, http://en.wikipedia.org/wiki/BSD_licenses)

*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#include <unistd.h>
#include <limits.h>


// added from realpath.c
#include <sys/param.h>
#include <errno.h>
#include <CoreServices/CoreServices.h>


#define OK      0
#define ERROR	1


static char directory[PATH_MAX+1] = {0};
static char curpath[2*PATH_MAX+2] = {0};
static char *curpath_ptr = curpath;
static char *p1 = 0;
static char *p2 = 0;
static unsigned long long int file_count = 0;


// prototype your functions
static unsigned int scan_dir(char *dir);
static char *resolveAlias(const char * pathToResolve);
static Boolean isFinderAlias(const char *pathname);
static char *resolveFinderAlias(const char *pathname);



int main(int argc, char * const argv[])
{

   //printf("sizeof(directory):  %zu\n", sizeof(directory));
   //printf("sizeof(curpath):  %zu\n", sizeof(curpath));

   if (argc != 2)
      return 1;

   char *pathToResolve = argv[1];
   char *resolvedPath = 0;

   // resolve symlinked or Mac-aliased input directory
   if (!(resolvedPath = resolveAlias(pathToResolve)))
   {
      fprintf(stderr, "failed: \"%s\"  %s\n", strerror(errno), pathToResolve);
      exit(1);
   }

   // get the last character of resolvedPath
   char *last_char_ptr = resolvedPath;
   while (*last_char_ptr) last_char_ptr++;   // last_char_ptr now points to the terminating '\0'
   --last_char_ptr;

   // add a trailing slash / if missing
   if (*last_char_ptr != '/')
   {
      strcat(directory, resolvedPath);
      strcat(directory, "/");
   }else{
      strcat(directory, resolvedPath);
   }

   scan_dir(directory);

   printf("%llu\n", file_count);

   return 0;

}


static unsigned int scan_dir(char *dir) 
{
   DIR *dirp;
   struct dirent *dp;
   int dir_len = 0;
   char *dir_len_ptr;

   FSRef ref;
   Boolean aliasFileFlag, folderFlag;


   // skip the /dev directory
   //if (strcmp(dir, "/dev/") == 0)
   //   return OK;
   // alternative
   if (
      ( dir[0] == '/' ) &&
      ( dir[1] == 'd' ) &&
      ( dir[2] == 'e' ) &&
      ( dir[3] == 'v' ) &&
      ( dir[4] == '/' )
      ) 
      return OK;


   // get the length of dir
   //dir_len = strlen(dir);
   // strlen alternative
   dir_len_ptr = dir;
   while(*dir_len_ptr++) dir_len++;

   if (!(dirp = opendir (dir))) 
   {
      fprintf (stderr, "\ninvalid directory: %s\n\n", dir);
      return 0;
   }


   // copy dir into curpath
   //strcpy(curpath, dir);
   // strcpy alternative
   curpath_ptr = curpath;
   while ( *dir ) { *curpath_ptr++ = *dir++; }
   *curpath_ptr = '\0';


   // cycle through the directories
   while ((dp = readdir(dirp)) != NULL) 
   {

      struct stat sp;

      // skip the . and .. entries
      if ((dp->d_name[0] == '.') && ( (dp->d_name[1] == '\0') ||
         ((dp->d_name[1] == '.') && (dp->d_name[2] == '\0'))))
         continue;


      // make the full name and do an lstat
      //strcat (curpath, dp->d_name);
      // strcat alternative
      p1 = curpath;   
      p2 = dp->d_name;
      while ( ( *p1 ) != 0 ) p1++;
      while ( ( *p1++ = *p2++ ) != 0);
      --p1;  // set pointer p1 to point to the first terminating ASCII nul '\0' character


      if (0 != lstat (curpath, &sp)) 
      {
         printf ("lstat error: %s\n", curpath);
         return ERROR;
      }


      // skip Mac-type aliases

      if (noErr == FSPathMakeRef((const UInt8 *)curpath, &ref, NULL)) 
      {
         if (noErr == FSIsAliasFile(&ref, &aliasFileFlag, &folderFlag)) 
         {
            if (aliasFileFlag)
            {
               curpath[dir_len] = '\0';
               continue;
            }
         }
      }


      // file counter
      if ((sp.st_mode & S_IFMT) == S_IFREG)
      {
         //printf("%s\n", curpath);
         file_count++;
         curpath[dir_len] = '\0';
         continue;
      }


/*
      // skip symbolic links
      if ((sp.st_mode & S_IFMT) == S_IFLNK)
      {
         curpath[dir_len] = '\0';
         continue;
      }
*/


      // recurse if we have a directory
      if ((sp.st_mode & S_IFMT) == S_IFDIR)  
      {

         //strcat (curpath, "/");
         // strcat alternative
         p1 = curpath;   
         p2 = "/";
         while ( ( *p1 ) != 0 ) p1++;
         while ( ( *p1++ = *p2++ ) != 0);
         --p1;  // set pointer p1 to point to the first terminating ASCII nul '\0' character

         if (scan_dir(curpath)) 
         {
            return ERROR;
         }
      }

      // null terminate the curpath so strncat works for the next entry
      curpath[dir_len] = '\0';

   } // end of while ... readdir

   closedir(dirp);

   return 0;

}  // scan_dir



static Boolean isFinderAlias(const char *pathname) 
{

   FSRef ref;
   Boolean aliasFileFlag, folderFlag;

   if (noErr == FSPathMakeRef((const UInt8 *)pathname, &ref, NULL)) 
   {
      if (noErr == FSIsAliasFile(&ref, &aliasFileFlag, &folderFlag)) 
      {
         return aliasFileFlag;
      }
   }

   return FALSE;

}


static char *resolveFinderAlias(const char *pathname) 
{
   FSRef ref;
   Boolean targetIsFolder, wasAliased;
   char *resolvedAlias;

   if (noErr == FSPathMakeRef((const UInt8 *)pathname, &ref, NULL)) 
   {
      if (noErr == FSResolveAliasFile(&ref, TRUE, &targetIsFolder, &wasAliased)) 
      {
         if (TRUE == wasAliased) 
         {
            if (NULL != (resolvedAlias = malloc(PATH_MAX + 1))) 
            {
               if (noErr == FSRefMakePath(&ref, (UInt8 *)resolvedAlias, PATH_MAX)) 
               {
                  errno = 0;
                  return resolvedAlias;
               }
               free(resolvedAlias);
            }
         }
      }
   }
	
   if (!errno)
      errno = ENOENT;

   return NULL;

}



static char *resolveAlias(const char * pathToResolve)
{

   char buffer[PATH_MAX+1];
   char *pathname;
   int err = EINVAL;


   if (isFinderAlias(pathToResolve)) 
   {
      if (NULL != (pathname = resolveFinderAlias( pathToResolve ))) 
      {	
         free(pathname);
         err = 0;
      }
   }


   if (err) 
   {
      if (NULL != (pathname = realpath(pathToResolve, buffer))) 
         err = 0;
   }

   if (err) 
      return NULL;
   else
      return pathname;

}




2. A file counter for Mac OS X using the Carbon File Manager API:

/*

countfiles -- count the number of Mac OS X files in a given directory (using the Carbon File Manager API)


Based on:

   Iterating Directory Contents: Iterating Directories in Carbon (FSGetCatalogInfoBulk), 
   http://developer.apple.com/documentation/Performance/Conceptual/FileSystem/Articles/IteratingFiles.html


Note: 

  - skips symbolic links and Mac-type (Finder) aliases
  - will also count sockets and FIFO files


compile with: 

gcc -std=c99 -Wall -Wextra -pedantic -O3 -framework CoreServices -o countfiles countfiles.c


Usage:

./countfiles ~
./countfiles ~/Desktop


Compare with:

/usr/bin/find -x ~ -type f -print0 | /usr/bin/tr -dc '\0' | /usr/bin/wc -c

*/


#include <stdio.h>
#include <CoreServices/CoreServices.h>


// Forward declarations.
OSStatus IterateFolder( FSRef * inFolder );
void DoSomethingWithThisObject( const FSCatalogInfo * inCatInfo );


static UInt8 path[1000];
static UInt32 pathSize = 1000;
static OSStatus status;

static const FSCatalogInfo * inCatInfo;
static FInfo * theFinderInfo;
static OSType type;
static Boolean aliasFileFlag, folderFlag;

static unsigned long long int file_count = 0;



int main(int argc, char * const argv[])
{
    OSStatus    outStatus;
    FSRef       folderRef;
 
    //printf("begin file iteration!\n");
    //fflush( stdout );

    if(argc != 2)
       return 1;


    // Get a folder path,
    // make it into an FSRef, and iterate it
    //
    outStatus = FSPathMakeRef((const UInt8 *) argv[1], &folderRef, NULL);

    if( outStatus == noErr )
    {
        outStatus = IterateFolder( &folderRef );
    }
 
    printf("%llu\n", file_count);

    printf( "final error status is (#%d)\n", (int)outStatus );


    return 0;

}
 
OSStatus IterateFolder( FSRef * inFolder )
{
    OSStatus outStatus;
 
    // Get permissions and node flags and Finder info
    //
    // For maximum performance, specify in the catalog
    // bitmap only the information you need to know
    FSCatalogInfoBitmap kCatalogInfoBitmap = (kFSCatInfoNodeFlags |
                                             kFSCatInfoFinderInfo);
 
    // On each iteration of the do-while loop, retrieve this
    // number of catalog infos
    //
    // We use the number of FSCatalogInfos that will fit in
    // exactly four VM pages (#113). This is a good balance
    // between the iteration I/O overhead and the risk of
    // incurring additional I/O from additional memory
    // allocation
    const size_t kRequestCountPerIteration = ((4096 * 4) / sizeof(FSCatalogInfo));
    FSIterator iterator;
    FSCatalogInfo * catalogInfoArray;

 
    // Create an iterator
    outStatus = FSOpenIterator( inFolder, kFSIterateFlat, &iterator );
 
    if( outStatus == noErr )
    {
        // Allocate storage for the returned information
        catalogInfoArray = (FSCatalogInfo *) malloc(sizeof(FSCatalogInfo) *kRequestCountPerIteration);

        FSRefPtr resultRefs = (FSRefPtr )malloc(sizeof(FSRef) * kRequestCountPerIteration);
        if (!resultRefs) {
             fprintf(stderr, "malloc failed for resultRefs\n");
             return 1;
        }

 
        if( catalogInfoArray == NULL )
        {
            outStatus = memFullErr;
        }
        else
        {
            // Request information about files in the given directory,
            // until we get a status code back from the File Manager
            do
            {
                ItemCount actualCount;
 
                outStatus = FSGetCatalogInfoBulk(iterator, kRequestCountPerIteration,
                                    &actualCount, NULL, kCatalogInfoBitmap,
                                    catalogInfoArray, resultRefs, NULL, NULL );
 
                // Process all items received
                if( outStatus == noErr || outStatus == errFSNoMoreItems )
                {
                    UInt32  index;
 
                    for( index = 0; index < actualCount; index += 1 )
                    {

                       inCatInfo = &catalogInfoArray[ index ];

  
                       // if we have a directory ...

                       if( (inCatInfo->nodeFlags & kFSNodeIsDirectoryMask) == kFSNodeIsDirectoryMask )
                       {

/*

                         // print directory path

                          status = FSRefMakePath(&resultRefs[index], path, pathSize);

                          if (status != noErr)
                          {

                             printf("FSRefMakePath failed %ld\n", outStatus);

                          }else{

                             printf("d %s\n", path);

                          }

*/

                          // recursive directory scanning
                          if (IterateFolder( &resultRefs[index] ))
                             continue;



                       // or else we have a file ...

                       } else {
                       
 
                          theFinderInfo = (FInfo *)&inCatInfo->finderInfo[0];
                          type = theFinderInfo->fdType;


                          // skip symbolic links
                          if ( 
                                (((type & 0xFF000000) >> 24) == 's')  &&
                                (((type & 0x00FF0000) >> 16) == 'l')  &&
                                (((type & 0x0000FF00) >> 8) == 'n')  &&
                                (((type & 0x000000FF)) == 'k')
                             )
                             continue;


                          // skip Mac-type aliases
                          if (noErr == FSIsAliasFile(&resultRefs[index], &aliasFileFlag, &folderFlag))
                          {
                            if (aliasFileFlag) 
                               continue;
                          }


                        
                         file_count++;     // file counter


/*

                         // print file path

                          status = FSRefMakePath(&resultRefs[index], path, pathSize);

                          if (status != noErr)
                          {

                             printf("FSRefMakePath failed %ld\n", outStatus);

                          }else{

                             printf("f %s\n", path);

                             //printf( "Found a file (type %c)\n", (char) ((type & 0xFF000000) >> 24));
                             //printf( "Found a file (type %c)\n", (char) ((type & 0x00FF0000) >> 16));
                             //printf( "Found a file (type %c)\n", (char) ((type & 0x0000FF00) >> 8));
                             //printf( "Found a file (type %c)\n\n", (char) (type & 0x000000FF));


                          }

*/


                       }  // if dir - else file

                    }  // for

                }  // if
 
 
            }
            while( outStatus == noErr );
 
            // errFSNoMoreItems tells us we have successfully processed all
            // items in the directory -- not really an error
            if( outStatus == errFSNoMoreItems )
            {
                outStatus = noErr;
            }
 
            // Free the array memory
            free( (void *) catalogInfoArray );
        }

    }  // if
 
    FSCloseIterator(iterator);
 
    return outStatus;
}




3. A Unix-based file counter with optional suffix filtering:
/*

countfiles -- count the number of regular (suffix-filtered) files in a given directory

compile with: 

gcc -std=c99 -Wall -Wextra -pedantic -O3 -o countfiles countfiles.c

Usage:

./countfiles -h
./countfiles ~/Desktop 2>/dev/null
./countfiles -v ~/Desktop 2>/dev/null
./countfiles -s '.c' ~/Desktop
./countfiles -v -s '.m' ~/Desktop


Note:

- countfiles does not scan a Mac-type (Finder) alias to a directory, i. e. it does not follow a Mac-type (Finder) alias to a directory.
- Files named '.' or '..' get scanned.
- File search will not descend into directories that have a different device number than the file from which the descent began.
- fts_options: FTS_COMFOLLOW | FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV | FTS_SEEDOT  (see man 3 fts)


For how to implement recursive directory scanning please see man 3 fts and:

   "fts(3) or Avoiding to Reinvent the Wheel",
   http://keramida.wordpress.com/2009/07/05/fts3-or-avoiding-to-reinvent-the-wheel/


Compare with:

/usr/bin/find -x ~ -type f -print0 | /usr/bin/tr -dc '\0' | /usr/bin/wc -c

*/


#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>
#include <unistd.h>      // getopt


static int  ptree(char * const argv[], const char *suffix, int verbose);

static void usage(void)
{

   static const char *usageinfo[] = { 
      "countfiles -- count the number of regular (suffix-filtered) files in a given directory", 
      "Usage:", 
      "countfiles [-hv] [-s suffix] [ [dir1] [dir2] ...]",
      "-h: help",
      "-s: suffix",
      "-v: verbose",
      "Note:",
      "- countfiles does not scan a Mac-type (Finder) alias to a directory, i. e. it does not follow a Mac-type alias to a directory.",
      "- Files named '.' or '..' get scanned.",
      "- File search will not descend into directories that have a different device number than the file from which the descent began.",
      "- fts_options: FTS_COMFOLLOW | FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV | FTS_SEEDOT  (see man 3 fts)"
   };


   fprintf(stderr, 

      "\n%s\n\n"
      "%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n"
      "\n%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n"
      "\t%s\n\n", 

      usageinfo[0], usageinfo[1], usageinfo[2], usageinfo[3], usageinfo[4], usageinfo[5], 
      usageinfo[6], usageinfo[7], usageinfo[8], usageinfo[9], usageinfo[10]

   );

}


int main(int argc, char * const argv[])
{

   int verbose = 0;
   const char *suffix = 0;

   if ( argc == 1 ) { usage(); return 0; }

   int ch;

   while ((ch = getopt(argc, (char **)argv, "s:hv")) != -1) 
   {
      switch (ch)
      {
         case 'h':
            usage();
            return 0;
         case 's':
            suffix = optarg;
            break;
         case 'v':
            verbose = 1;
            break;
         case '?':
            default:
            usage();
            return 1;
      }
   }

   argc -= optind;
   argv += optind;

   int rc;

   if ((rc = ptree(argv, suffix, verbose)) != 0) 
      rc = 1;

   return rc;

}


static int ptree(char * const argv[], const char *suffix, int verbose)
{

   int i;
   unsigned long long int file_count = 0;

   char *pathptr = 0;
   int equal = 0;
   size_t suffix_len = 0;

   FTS *ftsp = 0;
   FTSENT *p = 0, *chp = 0;

   //int fts_options = FTS_COMFOLLOW | FTS_PHYSICAL | FTS_XDEV | FTS_SEEDOT;
   int fts_options = FTS_COMFOLLOW | FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV | FTS_SEEDOT;

   int rval;
   rval = 0;

   if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL) 
   {
      warn("fts_open");
      return -1;
   }

   // Initialize ftsp with as many argv[] parts as possible.
   chp = fts_children(ftsp, 0);

   if (chp == NULL)
   {
      fprintf(stderr, "No files to traverse. See -h option. Exiting ...\n");
      return 1;
   }


   if (suffix)
   {
      
      suffix_len = strlen(suffix);

      while ((p = fts_read(ftsp)) != NULL) 
      {

         switch (p->fts_info) 
         { 

            case FTS_F:

                       //printf("%s\n", p->fts_path);

                       equal = 0;
                       pathptr = p->fts_path;
                       while (*pathptr) pathptr++;   // pathptr now points to the terminating '\0'

                       for (i = suffix_len - 1; i >= 0; i--) 
                       {
                          pathptr--;
                          if ( (!pathptr) || (*pathptr != suffix[i]) )
                          {
                             equal = 1;
                             break;
                          }
                       }

                       if (equal == 0)
                       {
                          file_count++;
                          if (verbose == 1)
                             printf("%s\n", p->fts_path);
                       }

                       break;

            default:
                       break;

         }   // switch

      }   // while


   }else{


      while ((p = fts_read(ftsp)) != NULL) 
      {

         switch (p->fts_info) 
         { 


            case FTS_F:

                       //printf("%s\n", p->fts_path);

                       file_count++;
                       break;

            default:
                       break;

         }   // switch

      }   // while

   }  // if-suffix-else


   fts_close(ftsp);

   if (verbose == 1)
   {

      if (suffix)
         printf("\ntotal number of files ending with %s is:  %llu\n\n", suffix, file_count);
      else
         printf("\ntotal number of files:  %llu\n\n", file_count);

   } else {

      printf("%llu\n", file_count);

   }

   return 0;

}  // ptree



Get full path to executing script

#!/opt/local/bin/bash

declare script_dir script_path

# realpath function for Mac OS X

# See also: 
# - realpath, http://my-sample-code.googlecode.com/svn/trunk/realpath/ (C snippet; resolves Mac aliases as well)
# - Create & resolve Mac-type aliases from the command line, http://codesnippets.joyent.com/posts/show/1745 
# - Compiling GNU coreutils on Mac OS X, http://codesnippets.joyent.com/posts/show/1799:
#   /usr/local/bin/gnureadlink -f "${1}"
#   port info coreutils
#   open http://www.gnu.org/software/coreutils/


function has_symlink() {

   declare basename path realpath

   path="${1}"   

   [[ "${path}" == '/' ]] && return 1

   #path="${path#/}"                     # trim a leading slash, if any
   #path="${path%/}"                     # trim a trailing slash, if any

   path="${path#"${path%%[!/]*}"}"       # trim leading slashes, if any
   path="${path%"${path##*[!/]}"}"       # trim trailing slashes, if any

   OIFS="${IFS}"
   IFS='/'

   for basename in $path; do
      realpath="${realpath%/}/${basename}"
      [[ -L "${realpath}" ]] && IFS="${OIFS}" && return 0
   done

   IFS="${OIFS}"

   return 1

}



function realpath() {

   declare basename currentpath dirstr optionstr path pathstr realpath
   declare -i var=0

   if [[ "${1}" == '-n' ]]; then optionstr='-n'; shift; fi


   # default to the current working directory
   # cf. help pwd; type -a pwd; type -p pwd; type -P pwd

   path="${1:-$(pwd -P)}"   


   if [[ "${path}" == '/' ]]; then 
      if [[ "${optionstr}" == '-n' ]]; then
         printf "%s" "${path}"
      else 
         printf "%s\n" "${path}"
      fi 
      return 0
   fi



   if [[ "${path:0:1}" == '.' ]]; then

      if [[ -d "${path}" ]]; then
         ( cd "${path}" 2>/dev/null || { echo "Could not cd to: ${path}"; return 1; } )
         [[ $? -ne 0 ]] && return 1
         path="$(cd "${path}"; pwd -P)"
      else
         dirstr="$(cd $(/usr/bin/dirname "${path}"); pwd -P)"
         pathstr="${dirstr}/$(/usr/bin/basename "${path}")"
         path="${pathstr}"
      fi

   fi


   if [[ "${path:0:1}" != '/' ]] && [[ "${path:0:1}" != '.' ]]; then 
      pathstr="$(pwd -P)/${path}"
      [[ ! -e "${pathstr}" ]] && pathstr="$(type -P ${path})"
      path="${pathstr}"
   fi


   #path="${path#/}"                     # trim a leading slash, if any
   #path="${path%/}"                     # trim a trailing slash, if any

   path="${path#"${path%%[!/]*}"}"       # trim leading slashes, if any
   path="${path%"${path##*[!/]}"}"       # trim trailing slashes, if any


   OIFS="${IFS}"
   IFS='/'

   for basename in $path; do

      realpath="${realpath%/}/${basename}"

      if [[ "${realpath}" == '/' ]]; then break; fi

      realpath="${realpath%/}"

      # cf. http://www.commandlinefu.com/commands/view/2369/find-broken-symlinks-and-delete-them
      [[ -L "${realpath}" ]] && [[ -n "$(/usr/bin/find -L "${realpath}" -type l -maxdepth 0 -print 2>/dev/null)" ]] && echo "Broken symlink: ${realpath}" && return 1
      [[ ! -e "${realpath}" ]] && echo "No such file or directory: ${realpath}" && return 1
      [[ ! -L "${realpath}" ]] && realpath="${realpath}" && continue

      while [[ -L "${realpath}" ]]; do
         currentpath="${realpath}"
         realpath="$(/usr/bin/readlink "${realpath}")"
         [[ "${realpath}" == '/' ]] && continue
         realpath="${realpath%/}"
      done


: <<-'COMMENT'

      while [[ -L "${realpath}" ]]; do
         currentpath="${realpath}"
         if [[ -d  "${realpath}" ]]; then
            realpath="$(cd "${realpath}"; pwd -P)"
         else
            realpath="$(/usr/bin/readlink "${realpath}")"
         fi
         [[ "${realpath}" == '/' ]] && continue
         realpath="${realpath%/}"
      done

COMMENT

      currentpath="${currentpath%/*}"   # get dirname

      if [[ "${realpath}" == '/' ]]; then
         realpath='/'
      elif [[ "${realpath:0:1}" == '/' ]]; then
         realpath="${realpath}"
      else
         realpath="${currentpath}/${realpath}"
      fi

   done   # for

   IFS="${OIFS}"

   # repeat the procedure if $realpath has a symbolic link element in it
   if has_symlink "${realpath}"; then 
      if [[ "${optionstr}" == '-n' ]]; then
         realpath -n "${realpath}"
         var=1
      else 
         realpath "${realpath}"
         var=1
      fi 
   fi

   [[ $var -eq 1 ]] && return 0

   if [[ "${optionstr}" == '-n' ]]; then
      printf "%s" "${realpath}"
   else 
      printf "%s\n" "${realpath}"
   fi 

   return 0

}



# man bash 2>/dev/null | less -p 'BASH_SOURCE'
[[ ${BASH_VERSINFO[0]} -le 2 ]] && echo 'The BASH_SOURCE array variable is only available for Bash 3.0 and higher!' && exit 1

[[ "${BASH_SOURCE[0]}" != "${0}" ]] && echo "script ${BASH_SOURCE[0]} is running sourced ..."



# cf. Bash get self directory trick,
# http://stevemorin.blogspot.com/2007/10/bash-get-self-directory-trick.html

###script_path="$(cd $(/usr/bin/dirname "${BASH_SOURCE[0]}"); pwd -P)/$(/usr/bin/basename "${BASH_SOURCE[0]}")"

script_dir="$(cd $(/usr/bin/dirname "${BASH_SOURCE[0]}"); pwd -P)"
script_path="${script_dir}/$(/usr/bin/basename "${BASH_SOURCE[0]}")"
script_path="$(realpath "${script_path}")"



if [[ ! -f "$script_path" ]]; then
   ###script_path="$(cd $(/usr/bin/dirname "$0"); pwd -P)/$(/usr/bin/basename "$0")"
   script_dir="$(cd $(/usr/bin/dirname "$0"); pwd -P)"
   script_path="${script_dir}/$(/usr/bin/basename "$0")"
   script_path="$(realpath "${script_path}")"
fi

[[ ! -f "$script_path" ]] && script_path="" && echo 'No full path to running script found!' && exit 1



# full path to executing script's directory
script_dir="${script_path%/*}"
echo "script_dir: ${script_dir}"


# full path to executing script
echo "script_path: ${script_path}"


exit 0