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!
-
You can pass it to your program as a command-line argument, or you can export it to your program as an environment variable. – Tom Karzes May 16 '19 at 19:14
-
thanks a lot for suggest, so to export it is something like `export VAR` , right? – gabriele May 16 '19 at 20:15
-
Right, it depends on the shell you use, but for sh and bash you would use `export`. Then you can use `getenv` from your C program. – Tom Karzes May 16 '19 at 20:48
3 Answers
Look up POSIX statvfs() and
<sys/statvfs.h>. The member described as shown sounds like the information you need:
unsigned long f_bsize— File system block size
That way, you don't need to rely on the user for the information; you can get the system to tell your program what you need to know.
- 730,956
- 141
- 904
- 1,278
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.
- 120,984
- 8
- 59
- 111
--block-size is a command line argument to ls:
--block-size=SIZE
with-l, scale sizes bySIZEwhen printing them; e.g.,--block-size=M; see SIZE format below
- 12,971
- 3
- 21
- 43
-
Maybe I forgot an important information (i'm gonna correct it in the question), my c program has to be runned from terminal with some options and file (something like ./program.c -l -R file1 dir1 file2 ecc.) but just this. So I need to get it from c with system call or something similar. Thanks anyway for your quick answer. – gabriele May 16 '19 at 20:06