Ben Bacarisse
4/5/2011 11:12:00 AM
Owner <Owner@Owner-PC.com> writes:
> What I'm trying to do with argv is
> swapping argv[0] to the end and files argument to the front
> reason I'm doing that is in English
> cmd options file... is nicely read
> do this(cmd) how(option) with file...
> but in my language
> it's more naturally read
> file.... option cmd
> so I'm playing around with my codes.
>
> this code below keeps changing argv[0] to file1
> can anyone find a fault code below?
>
> Thank you in advance.
>
> void hcmd(int argc, char *argv[])
> {
> int i, j;
> int opcount, agcount;
> char **k, **op, **ag;
> char *tmp;
> char *newarg[100];
>
> k = op = ag = argv;
The code makes not assignments to argv so any changes to it occur
through one of these three aliases.
> opcount = agcount = 0;
> /* Saving Command */
> *k = argv[0];
This has no effect so you might as well get rid of k althrogether (along
with j, tmp and newarg that are never even used).
>
>
>
> /* first Option */
> if (argc == 1) return;
argc can be < 1. However, I don't see why you want to do nothing when
argc == 1. I thought you would want to print argv[0] at least.
> i = 1;
>
> if (argv[i][0] == '-' || argv[i][0] == '/'){
> *op = argv[i++];
> opcount++;
> }
This set argv[0] (op is equal to argv so *op is an alias for
*argv).
> /* counting rest of options */
> for (;i < argc && argv[i][0] == '-' || argv[i][0] == '/';i++)
Turn up your compiler warning level! This means
(i < argv && argv[i][0] == '-')
||
(argv[i][0] == '/')
and so this loop can run too far.
> opcount++;
>
> /* first argument */
> if (i < argc){
> *ag = argv[i++];
and here you set argv[0] because ag is equal to argv.
> agcount++;
> }
>
> /* rest of argument */
> for (; i < argc; i++)
> agcount++;
>
> for(i=0; i< argc; i++)
> printf("%s ", argv[i]);
>
> }
If all you want to do is print argv in a different order, then there is
not need to go to all this effort:
void hcmd(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
if (argv[i][0] == '-' || argv[i][0] == '/')
printf("%s ", argv[i]);
for (i = 1; i < argc; i++)
if (argv[i][0] != '-' && argv[i][0] != '/')
printf("%s ", argv[i]);
if (argc > 0)
printf("%s", argv[0]);
}
--
Ben.