【Linux 应用编程】基础知识

it2022-05-09  43

错误提示

Linux 提供的系统调用API,通常会在失败的时候返回 -1。如果想获取更多更详细的报错信息,需要借助全局变量 errno 和 perror 函数:

#include <stdio.h> void perror(const char *s); #include <errno.h> const char *sys_errlist[]; int sys_nerr; int errno;

全局变量 errno

代码执行过程中发生错误时,Linux 会将 errno 这个全局变量设置为合适的值。errno 就是一个整数,对应系统中预先定义好的一个提示字符串。

perror 函数

perror 函数会读取 errno,然后找到预定义的提示字符串,最后将参数字符串、已定义的提示字符串拼接到一起,中间用冒号加空格分隔。相当于给错误信息加的注释。

示例

#include <stdio.h> #include <errno.h> #include <fcntl.h> int main() { char name[] = "non-exists.txt"; int ret = open(name, O_RDONLY); if (ret < 0) { printf("%d\n", errno); perror("this is my error"); } return 0; }

报错提示为:

2 this is my error: No such file or directory

命令行传参

C 程序的入口是 main 函数,其完整写法是包含两个参数的:

int main(int argc, char* argv[]);

其中第一个参数是命令行参数的个数,第二个参数是命令行参数数组。

例如下面这段代码:

#include <stdio.h> int main(int argc, char* argv[]) { printf("argc is: %d\n", argc); printf("argv[0] is: %s\n", argv[0]); }

执行的命令默认是第一个参数,所以无任何参数时的输出为:

argc is: 1 argv[0] is: ./a.out

可以借助 argc 来遍历所有的参数:

#include <stdio.h> int main(int argc, char* argv[]) { int i; printf("argc is: %d\n", argc); for (i = 0; i < argc; i++) { printf("argv[%d] is: %s\n", i, argv[i]); } }

执行命令,同时传入参数:

# ./a.out 666 hello world test haha argc is: 6 argv[0] is: ./a.out argv[1] is: 666 argv[2] is: hello argv[3] is: world argv[4] is: test argv[5] is: haha

转载于:https://www.cnblogs.com/kika/p/10851502.html


最新回复(0)