Skip to content

Commit

Permalink
Test fix for MoreShell
Browse files Browse the repository at this point in the history
  • Loading branch information
cnphil committed Apr 5, 2013
1 parent 0398ff0 commit 9db84f1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions MoreShell.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ main()
char buffer[256];
readline(0, buffer, 255);
buffer[strlen(buffer) - 1] = '\0'; // get rid of cr
strcpy(buffer, str_replace(buffer, "~", getenv("HOME")));
parse_argv(buffer, argv);
if(strcmp("exit", argv[0]) == 0) exit(0);
pid_t forkpid;
Expand Down
44 changes: 44 additions & 0 deletions readline.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,47 @@ readline(int fd, char *vptr, size_t maxlen)
*ptr = 0;
return(n);
}

char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements

if (!orig)
return NULL;
if (!rep || !(len_rep = strlen(rep)))
return NULL;
if (!(ins = strstr(orig, rep)))
return NULL;
if (!with)
with = "";
len_with = strlen(with);

for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}

// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);

if (!result)
return NULL;

while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}

0 comments on commit 9db84f1

Please sign in to comment.