我一直在学习C通过使用一些书,有一些代码,我不明白关于工作与基础在C编程。下面是代码:
/* By default, integers are decimal */
#define GN_ANY_BASE 0100 /* Can use any base - like strtol(3) */
#define GN_BASE_8 0200 /* Value is expressed in octal */
#define GN_BASE_16 0400 /* Value is expressed in hexadecimal */
// rlength: Read length bytes from the file, starting at the current file offset, and display them in text form.
int main(int argc, char *argv[]) {
fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); /* rw-rw-rw- */
if (fd == -1)
errExit("open");
for (ap = 2; ap < argc; ap++) {
switch (argv[ap][0]) {
case 'r': /* Display bytes at current offset, as text */
case 'R': /* Display bytes at current offset, in hex */
len = getLong(&argv[ap][1], GN_ANY_BASE, argv[ap]);
buf = malloc(len);
...
}
这是getLong
函数:
long getLong(const char *arg, int flags, const char *name) {
return getNum("getLong", arg, flags, name);
}
这是getNum
函数:
static long getNum(const char *fname, const char *arg, int flags, const char *name) {
long res;
char *endptr;
int base;
if (arg == NULL || *arg == 'n')
gnFail(fname, "null or empty string", arg, name);
base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 : (flags & GN_BASE_16) ? 16 : 10;
res = strtol(arg, &endptr, base);
return res;
}
这一行真的让我很困惑,之后发生的事情也没有帮助:
base = (flags & GN_ANY_BASE) ? 0 : (flags & GN_BASE_8) ? 8 : (flags & GN_BASE_16) ? 16 : 10;
它做了什么?我们为什么需要这个?GN_BASE
是什么?
我可以使用以下命令从终端运行程序:
./main file.txt r50
它将给出如下输出:
r50: this is a text inside file.txt
我试着为这个例子删除尽可能多的代码,希望它有助于清除这个例子。
我很抱歉事先问了你。非常感谢。- 参数
flag
可以携带其他信息,因此我们掩码我们对位运算符(&
)感兴趣的内容。顺便说一句,通常那些互斥标志是用左移来写的,而不是用绝对值(1<<6
,1<<7
,1<<8
)。 - 我们将提供的值映射为更方便内部使用的值(0100到0,200到8和0400到16)。 最后,如果没有找到这3个基位,我们提供默认值
10
。