Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / WinMobile

Utilities

4.89/5 (36 votes)
23 Jan 2012CPOL6 min read 80.5K   1.1K  
An article on simple but frequently used utility functions.

Introduction

I've come across countless situations where routinely used utility functions are simply not available and developers have to write and rewrite them many times over. This article will attempt to provide an array of static utility functions, bundled into a C++ class, that I have collected over the years and used repeatedly in over 50 projects of all shapes and sizes.

These functions are neither a break through in software engineering, nor are they the most optimized, lean and mean implementations. They are simply the most frequently used utility functions from my numerous projects, bundled in the most convenient manner, that has helped me and the developers working with me save many hundreds of hours.

The class and its function calls have evolved in the years to mimic something that has been most practical and convenient to use in all forms of C++ code, and their performance is usually adequate enough for most day-to-day project tasks.

Using the Code

Follow these simple steps to use the code in your Microsoft Visual Studio C++ project:

  1. Add the two files Util.h and Util.cpp into your project.
  2. Add the line #include "Util.h" in the top section of the *.cpp files you intend to use these utility functions in.
  3. Simply call the required static functions, e.g., CString strMyDocuments = CUtil::GetMyDocumentsDirectory().c_str().
  4. Check the "Util.cpp" source file to understand how each function works internally, they are very well commented.

List of Functions and Descriptions

File IO functions best suited for text files

In many projects, the only disk operations that need to be made are read/write operations of small to medium sized text files, usually in the form of log files, or files that store simple user data; on other projects, sizes of arbitrarily small/large files need to be reported or monitored and logged. In any case, these functions provide an easy way to achieve many of the routine file IO tasks that projects require. A few of those functions are listed below, please check the header file for all the available functions.

C++
static bool ReadFile(const _tstring& strFilePath, _tstring& strFileData)
static bool WriteFile(const _tstring& strFilePath, const _tstring& strFileData)

static long GetFileSize(const _tstring& strFilePath)
static __int64 GetFileSize64(const _tstring& strFilePath)

static bool IsFile(const _tstring& strFilePath)

String manipulation function, returns the number of successful sub-strings replaced

Sometimes the only thing that really needs to be done on strings is to find something and replace it with something else, and get to know how many of it there were! This function does exactly that and nothing more! There are also several similar functions for removing white spaces, garbage characters, and trimming.

It replaces all exact matches of strFind found in strSource with strReplace, and returns the number of replacements made.

C++
static long FindReplace(
    _tstring& strSource,
    const _tstring& strFind,
    const _tstring& strReplace)

String tokenizing functions

These are not the fastest or the most sophisticated string tokenizers on the planet; in fact, far from it! But, they are fast enough for most everyday string tokenizing needs, and they are very convenient to use.

C++
static long GetTokenCount(
    const _tstring& strSource,
    const _tstring& strDeliminator)

static _tstring GetToken(
    const _tstring& strSource,
    const _tstring& strDeliminator,
    long lTokenIndex)

Take this example, data from a file needs to be read, the file contains only numbers and new-line characters, you are interested in getting all the numbers, so this is what you can do:

C++
long lTokenIndex = 0;
long lTokenCount = (long) CUtil::GetTokenCount(strUserData, _T("\n"));

for(lTokenIndex = 0; lTokenIndex < lTokenCount; lTokenIndex++)
{
    long lNumber = _tstol(CUtil::GetTokenCount(strUserData, _T("\n"), 
                                               lTokenIndex).c_str());

    // Now you can do what ever you like with the number!
}

Clipboard: simple copy / paste text functions

C++
static void Copy2Clipboard(const _tstring& strData)
static _tstring PasteFromClipboard()

Numeric to string converters

There are countless times that numbers need to be converted to strings in any given project, from putting in file sizes and dates/times into log files, to reporting complex information in the GUI. These functions provide a convenient way to do that by simply using the function on the other side of a string += statement.

The first Long2String function outputs strings with leading 0s; e.g., Long2String(1234, 8); will give you "00001234". This is very useful when you need numbers to always have a set number of digits, like naming a sequence of files with consecutive numbers.

The Double2String function outputs strings with the specified number of digits after the decimal place, unless lPrecision is unspecified or set to 0 or lower, in which case, it doesn't truncate; e.g., Double2String(3.141592653); will return "3.141592653", whereas Double2String(3.141592653, 4); will return "3.1415".

C++
static _tstring Long2String(unsigned long lNumber, unsigned long lPrecision)
static _tstring Long2String(long long lNumber)

static _tstring Double2String(long double dNumber, unsigned long lPrecision = 0)

There are also useful function for finding the number of significant digits, rounding to a certain decimal place, and checking whether a number is a power of 2.

C++
static unsigned long NumberOfDigits(long lNumber)

static double Round(double dNumber2Round, unsigned long lPlaces)
static long Round(double dNumber2Round)

static bool IsPowerOf2(unsigned long iNumber)

String case converters, upper to/from lower

C++
static _tstring ToUpper(const _tstring& str)
static _tstring ToLower(const _tstring& str)

Compare without case sensitivity, returns 0 if both strings are equivalent when ignoring case

C++
static int CompareNoCase(const _tstring& str1, const _tstring& str2)

System time retrieval

It returns a string with the current system date/time in the requested format, which is very useful when logging or displaying date/time to users. A complete list of date/time format modifiers are available here.

C++
static _tstring GetSystemTime(
       const _tstring& strDateFormat = _T("%A, %d/%m/%Y, %H:%M:%S - %Z"))

Convert given number of seconds to hh:mm:ss and vice versa

Most of the time, measurements made or calculations done internally in a project are either in seconds or milliseconds, both of which are useless for logging and displaying to users; on top of that, if the user is required to enter time values, to her, seconds and milliseconds are usually meaningless. These functions provide simple ways to convert them between being meaningful to the user and being meaningful to the computer.

C++
static _tstring GetTime(long lSeconds)
static long GetTime(const _tstring& strTime = _T("00:00:00"))

Get commonly used directory paths

Commonly used user directory paths are not constant! They vary from computer to computer and user to user, that is why these functions are useful in quickly getting the directory you need to use in your code.

Please take a look at this article for details on the usage of these functions.

C++
static _tstring GetWorkingDirectory()
static _tstring GetProgramDirectory()
static _tstring GetProgramFilesDirectory()

static _tstring GetWindowsDirectory()
static _tstring GetSystemDirectory()

static _tstring GetMyDocumentsDirectory()
static _tstring GetMyMusicDirectory()
static _tstring GetMyPicturesDirectory()
static _tstring GetMyVideosDirectory()

static _tstring GetAppDataDirectory()
static _tstring GetLocalAppDataDirectory()

static _tstring GetDesktopDirectory()
static _tstring GetStartupDirectory()

Copy or cut a file into another directory

This function can either copy or cut a file into a directory, creating the entire directory structure of the destination, if necessary.

C++
static bool CopyFile2Directory(
    const _tstring& strSourceFilePath,
    const _tstring& strDestinationDirectory,
    bool bDeleteSource = false)

Directory manipulation functions

Please take a look at this article for more details about the "GetFileList" function.

C++
// Get list of all files in the target directory
static void GetFileList(
	const _tstring& strTargetDirectoryPath,
	const _tstring& strWildCard,
	bool bLookInSubdirectories,
	vector<_tstring>& vecstrFileList)

// Create the entire directory path
static void MakeDirectory(const _tstring& strDirectoryPath);

// Delete the entire directory path, including all files and folders within
static void DeleteDirectory(const _tstring& strTargetDirectoryPath)

// Check whether the given path is a directory
static bool IsDirectory(const _tstring& strDirectoryPath)

// Add "\" to the end of a directory path, if not present
static _tstring AddDirectoryEnding(const _tstring& strDirectoryPath)

// Remove "\" from the end of a directory path, if present
static _tstring RemoveDirectoryEnding(const _tstring& strDirectoryPath)

// Get the name of the directory form a given directory path:
// e.g. C:\Program Files\XYZ, will return XYZ
static _tstring GetDirectoryName(const _tstring& strDirectoryPath)

// Get the directory from a file path
static _tstring GetFileDirectory(const _tstring& strFilePath)

// Get the previous directory from a given directory path
static _tstring GetRootDirectory(const _tstring& strDirectoryPath)

// Get the file name including/excluding the extension from a given file path
static _tstring GetFileName(const _tstring& strFilePath, bool bIncludeExtension = false)

// Get the file extension including/excluding the "." from a given file path
static _tstring GetFileExtension(const _tstring& strFilePath, bool bIncludeDot = false)

// Get the file prefix / suffix
static _tstring GetFileNamePrefix(const _tstring& strFilePath, 
                const _tstring& strDelimiter);
static _tstring GetFileNameSuffix(const _tstring& strFilePath, 
                const _tstring& strDelimiter);

String type converters, ANSI to/from Unicode

These functions use the Win32 API functions WideCharToMultiByte() and MultiByteToWideChar() in a clean and convenient manner. You will also find commented out code within those functions that show other ways to do the conversions, but this commented out code works reliably only on the ASCII character set.

C++
static wstring GetStringW(const string& strA)
static string GetStringA(const wstring& strW)

Registry

Sometimes, all that needs to be done is read/write small pieces of data into the Registry, which doesn't need a heavy and fancy Registry editing tool or class.

C++
static _tstring GetRegistryInfo(
    HKEY hKey,
    const _tstring& strRegistryPath,
    const _tstring& strValueName)

static bool SetRegistryInfo(
    HKEY hkey,
    const _tstring& strRegistryPath,
    const _tstring& strValueName,
    const _tstring& strValue)

Usage example:

C++
_tstring strDirectory = GetRegistryInfo(
    HKEY_LOCAL_MACHINE,
    _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion"),
    _T("ProgramFilesDir"));

bool bSuccess = SetRegistryInfo(
    HKEY_LOCAL_MACHINE,
    _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion"),
    _T("ProgramFilesDir"),
    _T("C:\\Program Files"));

Internet

This function runs the default Internet browser application to open the given URL.

C++
static HINSTANCE OpenURL(LPCTSTR strURL)

Execution

Use this function to open files with their default applications, or run an executable with a set of input parameters.

C++
static bool Execute(
	const _tstring& strFilePath,
	const _tstring& strParameters = _T(""),
	bool bShow = true,
	bool bWait = false)

static bool Execute(
	const _tstring& strCommandLine,
	bool bShow = true,
	bool bWait = false)

Randomness generator

At random times, for random reasons, random things need to be generated!

C++
// Generate random string
static wstring GenerateRandomStringW(long lMaxLength, 
  bool bIncludeAlpha = true, bool bIncludeNumbers = true)
static string GenerateRandomStringA(long lMaxLength, 
  bool bIncludeAlpha = true, bool bIncludeNumbers = true)

// Generate random number between A & B
static float GetRandomNumber(float fA, float fB, float fGrain = 10.0f)
static double GetRandomNumber(double dA, double dB, double dGrain = 10.0)

// Simulate die roll in a bernoulli trial
static bool RollDice(double dProbability)

Hara Kiri

Sometimes the only way out is self destruction... This function simply deletes the program it is called from along with its parent directory.

C++
static void SelfDestruct()

Points of Interest

The code provided here is for unmanaged C++, is Unicode and ANSI compatible, and parts of it may be usable under other operating systems than Windows. If you find the code useful, please leave a comment, it could make my day :-)

History

  • V1.0 - Initial release.
  • V1.1 - Added several new functions and implemented a more user friendly interface as suggested by some developers.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)