Skip to content

Instantly share code, notes, and snippets.

@Alfex4936
Created March 7, 2021 09:17
Show Gist options
  • Select an option

  • Save Alfex4936/cb2e77cfbe3a79268288b7d615ff4409 to your computer and use it in GitHub Desktop.

Select an option

Save Alfex4936/cb2e77cfbe3a79268288b7d615ff4409 to your computer and use it in GitHub Desktop.
C: how to use command line arguments
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 1)
return 0;
int i;
size_t len = 0;
for (i = 1; i < argc; i++)
{
len += strlen(argv[i]);
if (argc > i + 1)
len++;
}
printf("length: %d\n", len);
char *cmd;
cmd = malloc(len);
cmd[0] = '\0';
for (i = 1; i < argc; i++)
{
strcat(cmd, argv[i]);
if (argc > i + 1)
strcat(cmd, " ");
}
free(cmd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment