4 Sep 2014
The split_line
function
#include <ctype.h>
/* split_line
* Breaks a string into a sequence of words. The pointer to each successive
* word is placed into an array. The function returns the number of words
* found.
*
* Parameters:
* buf - string to be broken up
* argv - array where pointers to the separate words should go.
* max_args - maximum number of pointers the array can hold.
*
* Returns: number of words found in string.
*/
int split_line(char *buf, char **argv, int max_args) {
int arg;
/* skip over initial spaces */
while (isspace(*buf)) buf++;
for (arg = 0; arg < max_args && *buf != '\0'; arg++) {
argv[arg] = buf;
/* skip past letters in word */
while (*buf != '\0' && !isspace(*buf)) buf++;
/* if not at line's end, mark word's end and continue */
if (*buf != '\0') {
*buf = '\0';
buf++;
}
/* skip over extra spaces */
while (isspace(*buf)) buf++;
}
return arg;
}
Linked list functions
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct list {
struct node *first;
};
/* list_create
* Creates an empty linked list.
*
* Returns: allocated list, holding nothing.
*/
struct list* list_create() {
struct list *ret;
ret = (struct list*) malloc(sizeof(struct list));
ret->first = NULL;
return ret;
}
/* list_remove
* Removes first occurrence of number from a linked list, returning
* 1 if successful
*
* Parameters:
* list - list from which item is to be removed.
* to_remove - number to be removed from the list.
*
* Returns: 1 if item was found and removed, 0 otherwise.
*/
int list_remove(struct list *list, int to_remove) {
struct node **cur_p;
struct node *out;
int cur_data;
cur_p = &(list->first);
while (*cur_p != NULL) {
cur_data = (*cur_p)->data;
if (cur_data == to_remove) {
out = *cur_p;
*cur_p = out->next;
free(out);
return 1;
}
cur_p = &((*cur_p)->next);
}
return 0;
}