Skip to content

Instantly share code, notes, and snippets.

@codedot
Created January 9, 2013 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codedot/4492253 to your computer and use it in GitHub Desktop.
Save codedot/4492253 to your computer and use it in GitHub Desktop.
Shell Word Expansions using wordexp() system interface
alexo@kuha:~/wordexp$ make
cc -o wordexp wordexp.c
./wordexp
echo hello world
0: 'echo'
1: 'hello'
2: 'world'
"\$HOME = $HOME" '$PWD'\ =\ $PWD
0: '$HOME = /home/alexo'
1: '$PWD = /home/alexo/wordexp'
alexo@kuha:~/wordexp$
.POSIX:
all: wordexp
./wordexp
clean:
-rm -f wordexp
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wordexp.h>
int main()
{
while (!feof(stdin)) {
char *words = NULL;
size_t len = 0;
char *newline;
wordexp_t res;
char **list;
int i, n;
getline(&words, &len, stdin);
newline = strchr(words, '\n');
if (newline)
*newline = '\0';
if (wordexp(words, &res, WRDE_SHOWERR))
exit(EXIT_FAILURE);
list = res.we_wordv;
n = res.we_wordc;
for (i = 0; i < n; i++)
printf("%d: '%s'\n", i, list[i]);
wordfree(&res);
free(words);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment