Skip to content

Instantly share code, notes, and snippets.

@ggrandes
Created April 11, 2016 00:52
Show Gist options
  • Save ggrandes/0aba1c31d104b0205deb5a414a49e571 to your computer and use it in GitHub Desktop.
Save ggrandes/0aba1c31d104b0205deb5a414a49e571 to your computer and use it in GitHub Desktop.
Readline C
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, stdin)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
line[read-1] = 0;
char **res = NULL;
char *p = strtok(line, " ");
int n_spaces = 0, i;
res = realloc(res, sizeof (char*) * ++n_spaces);
res[0] = argv[0];
// split string and append tokens to 'res'
while (p) {
res = realloc(res, sizeof (char*) * ++n_spaces);
if (res == NULL) {
exit(-1); // memory allocation failed
}
res[n_spaces-1] = p;
p = strtok(NULL, " ");
}
// print the result
for (i = 0; i < n_spaces; ++i) {
printf("token[%d] = %s\n", i, res[i]);
}
// free the memory allocated
free(res);
}
if (line) {
free(line);
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment