在 c 中访问 bash 局部变量
Access to bash local variable in c
我正在尝试用 C 重新制作一个 ls 命令;如果列出了目录内容,我需要复制 "total" 行(Unix ls 的做法)。
我知道它是文件大小的总和(不考虑软 link 和内部目录内容),四舍五入,除以局部变量 BLOCKSIZE,如果错误请纠正我。
问题是:BLOCKSIZE 到底是什么,我如何从终端检查它以及如何在 c 中获取它的值。
PS:我的 c 程序必须从 bash 运行,例如 ./program [options] {files},我不能将任何其他内容传递给 main 中的 argv。
提前致谢!
--block-size
是 command line argument 到 ls
:
--block-size=SIZE
with -l
, scale sizes by SIZE
when printing them; e.g.,
--block-size=M
; see SIZE format below
查找 POSIX statvfs()
和
<sys/statvfs.h>
。如图所示描述的成员听起来像您需要的信息:
unsigned long f_bsize
— 文件系统块大小
这样一来,您就无需依赖用户获取信息;你可以让系统告诉你的程序你需要知道什么。
来自 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
是一个环境变量。您使用 C 标准 getenv()
调用获取环境变量的值。
const char *blocksizestr = getenv("BLOCKSIZE");
if (blocksizestr == NULL) { /* no BLOCKSIZE variable */ }
int blocksize = atoi(blocksizestr);
另请注意,BLOCKSIZE
不会直接影响 ls
。 human_options()
和 human_readable()
函数中的 coreutils/ls.c. LS_BLOCK_SIZE
and BLOCK_SIZE
are. The BLOCKSIZE
environment variable is used inside gnulib/human.c 库没有引用它。 human_readable()
被 gnu 实用程序用来打印人类可读的输出。
我正在尝试用 C 重新制作一个 ls 命令;如果列出了目录内容,我需要复制 "total" 行(Unix ls 的做法)。 我知道它是文件大小的总和(不考虑软 link 和内部目录内容),四舍五入,除以局部变量 BLOCKSIZE,如果错误请纠正我。 问题是:BLOCKSIZE 到底是什么,我如何从终端检查它以及如何在 c 中获取它的值。 PS:我的 c 程序必须从 bash 运行,例如 ./program [options] {files},我不能将任何其他内容传递给 main 中的 argv。 提前致谢!
--block-size
是 command line argument 到 ls
:
--block-size=SIZE
with-l
, scale sizes bySIZE
when printing them; e.g.,--block-size=M
; see SIZE format below
查找 POSIX statvfs()
和
<sys/statvfs.h>
。如图所示描述的成员听起来像您需要的信息:
unsigned long f_bsize
— 文件系统块大小
这样一来,您就无需依赖用户获取信息;你可以让系统告诉你的程序你需要知道什么。
来自 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
是一个环境变量。您使用 C 标准 getenv()
调用获取环境变量的值。
const char *blocksizestr = getenv("BLOCKSIZE");
if (blocksizestr == NULL) { /* no BLOCKSIZE variable */ }
int blocksize = atoi(blocksizestr);
另请注意,BLOCKSIZE
不会直接影响 ls
。 human_options()
和 human_readable()
函数中的 coreutils/ls.c. LS_BLOCK_SIZE
and BLOCK_SIZE
are. The BLOCKSIZE
environment variable is used inside gnulib/human.c 库没有引用它。 human_readable()
被 gnu 实用程序用来打印人类可读的输出。