Click here to Skip to main content
15,879,474 members
Articles / Desktop Programming / MFC

Tiny C Runtime Library

Rate me:
Please Sign up or sign in to vote.
4.86/5 (60 votes)
25 Mar 20079 min read 331.7K   5.6K   123  
Reduce code bloat for those simple utility programs by using a streamlined C runtime - now with Unicode support!
// argcargv.cpp

// based on:
// LIBCTINY - Matt Pietrek 2001
// MSDN Magazine, January 2001

// 08/12/06 (mv)

#include <windows.h>
#include "libct.h"

#define _MAX_CMD_LINE_ARGS  32
TCHAR *_argv[_MAX_CMD_LINE_ARGS+1];
static TCHAR *_rawCmd = 0;

int _init_args()
{
	_argv[0] = 0;

	TCHAR *sysCmd = GetCommandLine();
	int szSysCmd = lstrlen(sysCmd);

	// copy the system command line
	TCHAR *cmd = (TCHAR*)HeapAlloc(GetProcessHeap(), 0, sizeof(TCHAR)*(szSysCmd+1));
	_rawCmd = cmd;
	if (!cmd)
		return 0;
	lstrcpy(cmd, sysCmd);

	// Handle a quoted filename
	if (*cmd == _T('"'))
	{
		cmd++;
		_argv[0] = cmd;						// argv[0] = exe name

		while (*cmd && *cmd != _T('"'))
			cmd++;

		if (*cmd)
			*cmd++ = 0;
		else
			return 0;						// no end quote!
	}
	else
	{
		_argv[0] = cmd;						// argv[0] = exe name

		while (*cmd && !_istspace(*cmd))
			cmd++;

		if (*cmd)
			*cmd++ = 0;
	}

	int argc = 1;
	for (;;)
	{
		while (*cmd && _istspace(*cmd))		// Skip over any whitespace
			cmd++;

		if (*cmd == 0)						// End of command line?
			return argc;

		if (*cmd == _T('"'))					// Argument starting with a quote???
		{
			cmd++;

			_argv[argc++] = cmd;
			_argv[argc] = 0;

			while (*cmd && *cmd != _T('"'))
				cmd++;

			if (*cmd == 0)
				return argc;

			if (*cmd)
				*cmd++ = 0;
		}
		else
		{
			_argv[argc++] = cmd;
			_argv[argc] = 0;

			while (*cmd && !_istspace(*cmd))
				cmd++;

			if (*cmd == 0)
				return argc;

			if (*cmd)
				*cmd++ = 0;
		}

		if (argc >= _MAX_CMD_LINE_ARGS)
			return argc;
	}
}

void _term_args()
{
	if (_rawCmd)
		HeapFree(GetProcessHeap(), 0, _rawCmd);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Mike_V is currently a student at UCLA.

After a few years on the Dark Side, he reformed and now chants "Death to VB." His computer-related interests include C++, C#, and ASP.NET (in C#, of course). He writes operating systems in C++ and assembler as a hobby.

Comments and Discussions