0

Is there a better way to take in inputs, For example: ls = list all files in the current dir ... cat Q1.c will display etc

To me it seems like I'm hard coding it at this point

int main(int argc, char *argv[])
{    
    int i;
    char *dest = NULL;
    if(argc==1) {
        printf( "No arguments were passed.\n" );
    } 
    else {
        printf("Arguments:\n");
        for(i=1;i<argc;++i) {
            printf("%d. %s\n", i, argv[i]);
            dest = malloc(strlen(argv[i])+1);
            if(i<2) {
                sprintf(dest, "%s",argv[i]);    
            }
            else {
                sprintf(dest, "%s %s", argv[i-1], argv[i]); 
            }
        }   
        mysystem(dest);
    }
    return 0;
}
Schwern
  • 153,029
  • 25
  • 195
  • 336
Semko
  • 19
  • 7

2 Answers2

1

As Bruce told in the comments I am guessing that you are looking for a quick parser for this options. getopt() and getopt_long() will let you parse your arguments with ease but notice that these are members of POSIX!


getopt(): ./example -a udp://127.0.0.1:8000

getopt_long(): ./example --address=udp://127.0.0.1:8000

caiomcg
  • 501
  • 10
  • 23
1

You weren't building up the buffer for mysystem. Here's the working code [please pardon the gratuitous style cleanup]:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

int
main(int argc, char *argv[])
{
    int i;
    char *dest = NULL;
    char *dp;
    char *av;
    int totlen;
    int len;

    if (argc == 1) {
        printf("No arguments were passed.\n");
    }

    else {
        // get total amount of space we'll need
        totlen = 0;
        for (i = 1; i < argc; ++i) {
            av = argv[i];
            len = strlen(av);
            totlen += len + 1;
        }

        dest = malloc(totlen + 1);
        dp = dest;
        *dp = 0;

        printf("Arguments:\n");
        for (i = 1; i < argc; ++i) {
            av = argv[i];

            printf("%d. %s\n", i, av);

            if (i > 1)
                *dp++ = ' ';

            strcpy(dp,av);
            dp += strlen(av);
        }

        system(dest);
    }

    return 0;
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • You're welcome! I hope that the differences between your original code and my adjustments are clear enough for you to understand what I did and why. Anyway, Happy Programming! – Craig Estey Feb 02 '16 at 00:15