C函数strerror
返回错误描述字符串,如此处所述.示例字符串
No such file or directory
问题是这些字符串定义在哪里?我查看了我的头文件,但没有看到任何内容.
它们被定义在C库的某个地方,传统上是一个char*
被称为sys_errlist
长度的全局数组sys_nerr
,至少在Unix系统上.
因为之前编写的遗留程序strerror
是标准化的,可以直接访问这个数组,它甚至可以在现代GNU/Linux和Mac OS X上用于向后兼容(尽管除了通过perror
或者你真的不应该访问它strerror
).
例如,这是Mac OS X 10.8.2的定义sys_errlist
.
包含错误消息的头文件被命名为 errmsg.h
00012 const char *const sys_errlist[] = {
00013 "Operation succeeded", /* 0 */
00014 "Invalid argument", /* EINVAL */
00015 "Bad memory address", /* EFAULT */
00016 "String too long", /* ENAMETOOLONG */
00017 "Out of memory", /* ENOMEM */
00018 "Input/output error", /* EIO */
00019 "No such file or directory", /* ENOENT */
00020 "Not a directory", /* ENOTDIR */
00021 "Is a directory", /* EISDIR */
00022 "File or object exists", /* EEXIST */
00023 "Cross-device link", /* EXDEV */
00024 "Try again later", /* EAGAIN */
00025 "Illegal seek", /* ESPIPE */
00026 "Unimplemented feature", /* EUNIMP */
00027 "Device not available", /* ENXIO */
00028 "No such device", /* ENODEV */
00029 "Device or resource busy", /* EBUSY */
00030 "Invalid/inappropriate ioctl",/* EIOCTL (ENOTTY in Unix) */
00031 "Directory not empty", /* ENOTEMPTY */
00032 "Result too large", /* ERANGE */
00033 "No space left on device", /* ENOSPC */
00034 "Too many open files", /* EMFILE */
00035 "Too many open files in system",/* ENFILE */
00036 "No such system call", /* ENOSYS */
00037 "File is not executable", /* ENOEXEC */
00038 "Argument list too long", /* E2BIG */
00039 "Bad file number", /* EBADF */
00040 };
Run Code Online (Sandbox Code Playgroud)
如您所见,这取决于 libc 实现。但总体思路是相同的:某些数组包含从错误号到最大长度为 1024 字节的字符串的映射。
其他实现:
http://fossies.org/dox/glibc-2.16.0/stdio-common_2errlist_8c_source.html