【Linux 应用编程】基础知识

错误提示

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

#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,而后找到预约义的提示字符串,最后将参数字符串、已定义的提示字符串拼接到一块儿,中间用冒号加空格分隔。至关于给错误信息加的注释。svg

示例

#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 函数,其完整写法是包含两个参数的:this

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

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

例以下面这段代码:命令行

#include <stdio.h>

int main(int argc, char* argv[])
{
    printf("argc is: %d\n", argc);
    printf("argv[0] is: %s\n", argv[0]);
}

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

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

能够借助 argc 来遍历全部的参数:xml

#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]);
    }
}

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

# ./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