porting bash func for truncating home dir to C (mostly for practice)

This commit is contained in:
Dan Buch 2012-04-09 08:25:52 -04:00
parent f9b76d6027
commit 4d0d973c8d
3 changed files with 78 additions and 1 deletions

View File

@ -1 +1,2 @@
/temperatures
/truncpwd

View File

@ -1,5 +1,5 @@
CFLAGS += -g -Wall -Wextra
all: temperatures
all: temperatures truncpwd
.PHONY: all

76
digressions/truncpwd.c Normal file
View File

@ -0,0 +1,76 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#define BUFSIZE 2048 + 1
#define DEFAULT_TRUNCPWD_LEN "40"
void substr(char *dest, char *src, int offset, int len) {
int i;
for (i = 0; i < len && src[offset + i] != '\0'; i++) {
dest[i] = src[offset + i];
}
dest[i] = '\0';
}
void with_home_as_tilde(char *dest, char *src, char *home) {
size_t src_len = strlen(src);
size_t home_len = strlen(home);
if (strncmp(src, home, home_len) == 0) {
char less_home[BUFSIZE];
substr(less_home, src, home_len, src_len - home_len);
sprintf(dest, "~%s", less_home);
} else {
sprintf(dest, "%s", src);
}
}
int main(void)
{
char pwd[BUFSIZE];
const char *home = getenv("HOME");
const char *truncpwd_len_str = getenv("TRUNCPWD_LEN");
if (truncpwd_len_str == NULL) {
truncpwd_len_str = DEFAULT_TRUNCPWD_LEN;
}
unsigned int truncpwd_len = (unsigned int)atoi(truncpwd_len_str);
const char *truncpwd_leader = getenv("TRUNCPWD_LEADER");
if (truncpwd_leader == NULL) {
truncpwd_leader = "...";
}
if (getcwd(pwd, sizeof(pwd)) == NULL) {
fprintf(stderr, "truncpwd: %s\n", strerror(errno));
return 1;
}
size_t pwd_len = strlen(pwd);
if (strncmp(home, pwd, pwd_len) == 0) {
printf("~\n");
}
char tilde_subbed[BUFSIZE];
with_home_as_tilde(tilde_subbed, pwd, (char *)home);
size_t tilde_subbed_len = strlen(tilde_subbed);
if (tilde_subbed_len <= truncpwd_len) {
printf("%s\n", tilde_subbed);
return 0;
} else {
char last_n[truncpwd_len + 1];
int offset = tilde_subbed_len - truncpwd_len + 1;
substr(last_n, tilde_subbed, offset, truncpwd_len + 1);
printf("%s%s\n", truncpwd_leader, last_n);
}
return 0;
}