3 ms·
Some additional stuff which jumped out at me, on top of leif's excellent collection: + cwd[] should be MAXPATHLEN bytes long + if you want people to use it, y
by JoachimSchipper 14y ago
Some additional stuff which jumped out at me, on top of leif's excellent collection:
+ cwd[] should be MAXPATHLEN bytes long
+ if you want people to use it, you need to put some license on it. GPL and ISC (simplified BSD) are good choices.
+ you may wish to consider asprintf() and err() (both of which elegantly solve a problem that leif has pointed out). These functions are non-POSIX but widely supported and easily portable. (You can also learn how to use the autotools to handle OSes that do not have these functions.)
+ getopt_long() may be easier than parsing parameters "by hand", especially once your utility grows more parameters.
+ hardcoding the colours is ok for now, but you should really use terminfo to find the appropriate escape sequence. The "magic word" for setting the foreground colour is "setaf"; you may wish to look at terminfo(3) and the source code for tput, if your OS has that utility. Warning: proper terminal handling is complex.
- lubutu 14y ago"cwd[] should be MAXPATHLEN bytes long" This is actually a common mistake — PATH_MAX and the like are not guaranteed to be defined. In fact, in POSIX it is literally impossible to ever know whether your buffer is long enough. Your best bet is, #ifdef PATH_MAX char cwd[PATH_MAX]; long len = sizeof cwd; #else char *cwd; long len; if((len = pathconf(".", _PC_PATH_MAX)) < 0) len = 8192; /* some arbitrary value */ cwd = malloc(len); #endif This is probably one of the ugliest parts of POSIX.
- tptacek 14y agoI think it's a little strange to take someone to task for using C99 snprintf and then turn around and tell them to use asprintf. The reality is that both snprintf and asprintf are equally portable --- there was a window in the '90s where snprintf was by itself not portable, and projects routinely carried it along. This is all academic though; dynamic sizing for a buffer containing a Unix path passed in on the command line? Professional code would just use PATH_MAX or whatever and be done with it. I see downthread that there are concerns about path limits, but since so much of the rest of Unix doesn't care about that particular problem, I'm not sure what the win is trying to optimize it.
- deleted 14y ago[deleted]