473,396 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Commandline argh [sic] processing

Opinion please.

The code below is an attempt at demonstrating commandline arg processing.

I don't really like the repetitive use of ...

if(!(*s))
{
// Make sure we don't go out of bounds.
//
p = i + 1 >= argc ? NULL : argv[++i];
}

and, of course, I'm not sure the code is either 'sound' or optimal for what
it does.

Feedback welcome.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define trace(...) printf(__VA_ARGS__)

void usage(void);

// Tested with [as noise and signal]
//
// -f test.c -a -B --n 10 -ftest1 -n50 - f three -k
//
// as args.

int main(int argc, char * argv[])
{
// Holds the switch char, e.g., given -f, this will be 'f' when it
matters.
//
char c = 0;

// Used to point at an argv.
//
char * s = NULL;
char * p = NULL;

// A buffer for the -f switch implementation to use.
//
char buffer[100];

// A number for the -n switch implementation to use.
int num = 0;

// Loop counter for argc handling.
//
int i = 0;

// If we've no useful args, tell the user [will exit].
//
if(argc <= 1)
{
usage();
}

// For each arg ...
//
for(i = 1; i < argc; ++i)
{
s = argv[i];

p = NULL;

// If this argv is a valid switch? The first char needs to be a /
or a -,
// and the following part must contain one of the chars we
expect. The
// leading @ in the test string is important as it's acting as a
'guard'..
// we don't want to return 0 if we find a valid char basically, so
[0] has
// a character we shouldn't find.
//
if((*s == '/' || *s == '-') && strcspn("@abfnABFN", ++s))
{
// For each char after the / or - .... !p is there because if
the
// 'meat' of the switch directly follows the flag character,
this
// while loop will iterate through the non-switch-char
characters.
//
while((c = *s++) && !p)
{
switch(toupper(c))
{
case '?':

usage();

break;
case 'A':

trace("-A switch found\n");

break;
case 'B':

trace("-B switch found\n");

break;
case 'F': // -f indicates there's a string
parameter coming.

trace("-F switch found\n");

{
// If there's a '\0' following 'F', then the
string
// we're wanting should be in the next argv as
this
// argv is terminated.
//
if(!(*s))
{
// Make sure we don't go out of bounds.
//
p = i + 1 >= argc ? NULL : argv[++i];
}

// No terminator, so the filename is flush up
against the -f - or was not given!
//
else

{
p = s;
}

if(!p)
{
fprintf(stderr, "\t-F: but no filename
found!\n");
}

else

{
strncpy(buffer, p, sizeof(buffer));

trace("\tfilename: %s\n", buffer);
}
}
break;

case 'N': // -n indicates there's a numeric
parameter coming [expected].

trace("-N switch found\n");

{
if(!(*s))
{
p = i + 1 >= argc ? NULL : argv[++i];
}

else

{
p = s;
}

if(!p)
{
fprintf(stderr, "\t-N: but no integer
found!\n");
}

else

{
sscanf(p, "%d", &num);

trace("\tvalue: %d\n", num);
}
}
break;

default:

trace("\nShouldn't get here ... unknown or badly
formatted flag!: argv[%d] = '%s'\n\n", i, argv[i]);

break;
}
}
}
else
{
trace("\n\tOther params ... input file etc?: %s\n\n", s);
}
}

getchar();

return EXIT_SUCCESS;
}
void usage(void)
{
puts("Usage:\n\n");
puts("\t-a, -b : test switches");
puts("\t-f<filename> : test switch with a string parameter");
puts("\t-n<num> : test switch with a numeric parameter");

exit(0);
}


--
==============
*Not a pedant*
==============
Mar 23 '06 #1
3 1840
"pemo" <us***********@gmail.com> writes:
The code below is an attempt at demonstrating commandline arg processing.

I don't really like the repetitive use of ...

if(!(*s))
{
// Make sure we don't go out of bounds.
//
p = i + 1 >= argc ? NULL : argv[++i];
}


I would suggest writing a helper function or two. There are
many, *many* libraries and examples out there for helping out
with command-line processing. I'm sure you can find one you
like.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Mar 23 '06 #2

"pemo" <us***********@gmail.com> wrote in message
news:dv**********@news.ox.ac.uk...
Opinion please.

The code below is an attempt at demonstrating commandline arg processing.

I don't really like the repetitive use of ...

if(!(*s))
{
// Make sure we don't go out of bounds.
//
p = i + 1 >= argc ? NULL : argv[++i];
}


You are reinventing getopt. But, that's okay. I've done it myself.

I'd suggest the following:

1) using argv[i][j] will save some grief over using s & p
2) loop from 0 to argc, determine which argv's are flag args using strstr
and/or strspn, storing the results in an flag indicator array and requoting
args if necessary
3) loop from 0 to argc, if flag array indicates arg is a flag, switch to
appropriate setup routine ( At this point, I usually setup a control array
where a value representing the selected option indexes into the control
array returning the correct argv position. The control array can then be
selectively used throughout your program to include or exclude code and you
have access to the correct argv values immediately.)
Rod Pemberton
Mar 23 '06 #3

"Rod Pemberton" <do*********@sorry.bitbuck.cmm> writes:
"pemo" <us***********@gmail.com> wrote in message
news:dv**********@news.ox.ac.uk...
Opinion please.

The code below is an attempt at demonstrating commandline arg processing.

I don't really like the repetitive use of ...

if(!(*s))
{
// Make sure we don't go out of bounds.
//
p = i + 1 >= argc ? NULL : argv[++i];
}


You are reinventing getopt. But, that's okay. I've done it myself.

I'd suggest the following:

1) using argv[i][j] will save some grief over using s & p
2) loop from 0 to argc, determine which argv's are flag args using strstr
and/or strspn, storing the results in an flag indicator array and requoting
args if necessary
3) loop from 0 to argc, if flag array indicates arg is a flag, switch to
appropriate setup routine ( At this point, I usually setup a control array
where a value representing the selected option indexes into the control
array returning the correct argv position. The control array can then be
selectively used throughout your program to include or exclude code and you
have access to the correct argv values immediately.)


One can also use the fact that argv[argc] is a NULL pointer.
Mar 24 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: nick | last post by:
Hi all: In the winform i want to run commandline with return value(string), then display this string in winform textbox. anyone has idea about that? Thanks Nick
1
by: Rvo | last post by:
I'm writing an application that should work both as a GUI and a commandline program. When running from commandline I want to give all output to the commandline instead of showing it it an own...
5
by: jcrouse | last post by:
I have the following code: Dim MyStartupArguments() As String MyStartupArguments = System.Environment.GetCommandLineArgs UBound(MyStartupArguments) RomName =...
2
by: Christoph Borger | last post by:
Hello! I have wrote a windows service in vb.net. This service monitors the running processes with WMI and the Win32_Process class. Till last month all seems ok. But since the begin of september...
1
by: ritesh.noronha | last post by:
Hi Group, I have a question regarding the commandline options of msbuild. I am currently using msbuild to build projects using the existing solution files. These solution files have references...
0
by: axlq | last post by:
While trying to learn the ins and outs of the php CURL library, I decided to write a php script that posts a form on the Chicago Board of Options (CBOE) web site, which returns an ASCII text file. ...
1
by: RSH | last post by:
Hi, I have a silly question... I have a Windows Form project (VB.Net) that was created in Visual Studio 2003. The project runs great. Now I have to add the ability to run the same...
1
by: edmondsnake | last post by:
Dear all, I would like to ask questions about my VB.net program. The executable file of the program is called "PSP.exe" Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As...
2
by: andreas.huesgen | last post by:
Hello, I am writing a commandline tool in Python which is often feed with lots of commandline arguments. In practice, the commandline already reached a critical length which is to long for Windows...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.