Search code examples
cbashls

Access to bash local variable in c


I'm trying to remake an ls command in C; I need to replicate a "total" row if directory content is listed (exactly how Unix ls does). I know it's the sum of file size(without considering soft link and inner directory contents), rounded up, divided by the local variable BLOCKSIZE, correct me if it's wrong. The questions are: what BLOCKSIZE exactly is, how can i check it from terminal and how get its value in c. PS: my c program has to be runned from bash like ./program [options] {files}, I can not pass anything else to argv in main. Thanks in advance!


Solution

  • From GNU coreutils:

    The default block size is chosen by examining the following environment variables in turn; the first one that is set determines the block size.
    ....
    BLOCKSIZE

    BLOCKSIZE is an environment variable. You get the value of environment variables using the C standard getenv() call.

     const char *blocksizestr = getenv("BLOCKSIZE");
     if (blocksizestr == NULL) { /* no BLOCKSIZE variable */ }
     int blocksize = atoi(blocksizestr);
    

    Also note that BLOCKSIZE does not affect ls directly. It's nowhere referenced from coreutils/ls.c. LS_BLOCK_SIZE and BLOCK_SIZE are. The BLOCKSIZE environment variable is used inside gnulib/human.c library inside the human_options() and from human_readable() functions. The human_readable() is used by gnu utilities to print human readable output.