Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Tiny C Runtime Library

, 25 Mar 2007
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

Share

About the Author

Mike_V

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.

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 25 Mar 2007
Article Copyright 2006 by Mike_V
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid