In my eyes most of the GNU stuff is bloated and doesn't really fit my view of how a Linux environment should look like. I have come up with my own minimalist implementation of the GNU Coreutils, but I have not touched C in a long time and my programming style reflects that a little.
rmdir.c is a good representation of it throughout the project:
#include <sys/stat.h>
#include <sys/types.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <errno.h>
#include <string.h>
void process_path(char *path, bool verbose, bool parents);
int main(int argc, char** args){
bool verbose = false;
bool parents = false;
char c;
while ((c = getopt(argc, args, "vpr")) != -1){
switch(c){
case 'r':
case 'p': parents = true; break;
case 'v': verbose = true; break;
default: return -1;
}
}
/* Proccess each path in the remaining arguments */
int index;
for (index = optind; index < argc; index++){
process_path(args[index], verbose, parents);
}
return 0;
}
void remove_dir(char *path, bool verbose){
int ret = rmdir(path);
if(verbose){
if(ret == -1) printf("rmdir: could not remove '%s' %s \n", path, strerror(errno));
if(ret == 0) printf("rmdir: removed directory '%s' \n", path);
}
}
void do_parents(char *path, bool verbose){
while(1) {
remove_dir(path, verbose);
char *p = strrchr(path, '/');
if(p == NULL) break;
*p = '\0';
}
}
void process_path(char *path, bool verbose, bool parents){
switch(parents){
case false: remove_dir(path, verbose); break;
case true: do_parents(path, verbose); break;
}
}
Statically linked against musl-libc, the executable is only 18KiB, as opposed to the GNU version 39KiB.
Any ideas on how I can improve the coding style or make things even smaller?
rmdir
into therm
utility, as in Plan9. (C source here.) The same program was ported to Unix-likes in Plan 9 from User Space. (That source is here.) \$\endgroup\$ – Anko Aug 30 '14 at 22:12rmdir
itself is bloated, but "most of the GNU stuff". But on an embedded system where you sometimes measure the available space is mega- or even kilobytes, 39KiB are quite a lot for this simple tool. Even 18KiB is way more than would be really needed. For comparison: I once did a minimalmount
with optional-t
support for an embedded Linux system in assembler: executable is 1152 bytes, help and six error messages included. \$\endgroup\$ – DarkDust Aug 30 '14 at 22:43