简体   繁体   English

unistd.h库的getopt()函数

[英]unistd.h library's getopt() function

I'm currently trying to make my own version of getopt() function. 我目前正在尝试制作自己的getopt()函数版本。 But I do not know how it returns a character type as an int type. 但是我不知道它如何将字符类型返回为int类型。

Is there any way I can have a look into the source code of the getopt() function? 有什么办法可以让我了解getopt()函数的源代码吗?

The source code of getopt() in glibc is here: https://github.com/lattera/glibc/blob/master/posix/getopt.c glibcgetopt()的源代码在这里: https : //github.com/lattera/glibc/blob/master/posix/getopt.c

Of course there are more implementations you might look at, but this is probably the most popular one. 当然,您可能会看到更多的实现,但这可能是最受欢迎的实现。 Here's another, from FreeBSD: https://github.com/lattera/freebsd/blob/master/lib/libc/stdlib/getopt.c 这是来自FreeBSD的另一个: https : //github.com/lattera/freebsd/blob/master/lib/libc/stdlib/getopt.c

The return value of getopt(3) function is int to allow for an extra value (apart of all the possible char s it returns) to mark the end of options condition. getopt(3)函数的返回值是int以允许使用额外的值 (它返回的所有可能char的一部分)来标记选项条件的结束。 This extra value is EOF (as in getchar(3) function) which must be different from any char possible value. 这个额外的值是EOF (如在getchar(3)函数中一样),该值必须与任何可能的char值不同。

To deal with this and the possibility of different C compilers implement char either as signed or unsigned , both functions implement the return value as the character value as an unsigned byte from 0 to 255 (by mapping all the negative values to positive, this is adding to the negative values the constant 256 ---this is an example, as the language doesn't specify exactly how this is done---, so the negatives go in the range 128..255 ), and reserve EOF as the value -1 . 为了解决这个问题,不同的C编译器可能以有signedunsigned实现char ,这两个函数都将返回值作为字符值实现为从0255unsigned byte (通过将所有负值映射为正,这是在添加到负值,常量256 ---这是一个示例,因为语言没有确切说明如何完成操作---所以负值在128..255的范围内,并保留EOF作为值-1

If you are writing a getopt(3) function to be integrated in your system's standard c library, just check what value is used for EOF (most probable is -1 ) and then implement it so the values returned for your default char type don't conflict/overlap with/ it. 如果您要编写将getopt(3)函数集成到系统的标准c库中,则只需检查EOF使用了什么值(最有可能是-1 ),然后实施它,以便为默认char类型返回的值不与它冲突/重叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM