用perror()或strerror()打印错误信息

perror() 和 strerror() 以一种直观的方式打印出错误信息,对于调试程序和编写优秀的程序非常有用。

下面是perror() 与 strerror() 的使用范例及区别:

perror()原型:

#include <stdio.h>

void perror(const char *s);

其中,perror()的参数s 是用户提供的字符串。当调用perror()时,它输出这个字符串,后面跟着一个冒号和空格,然后是基于当前errno的值进行的错误类型描述。范例见下。

strerror()原型:

#include <string.h>

char * strerror(int errnum);

这个函数将errno的值作为参数,并返回一个描述错误的字符串。范例见下error-example.c。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>	/* for strerror() */
#include <errno.h>  /* for errno */
int main()
{
	FILE *fp;
	
	fp = fopen("./foo/bar", "r");
	if (fp == NULL)
	{
		perror("I found an error");
	}

	fp = fopen("./foo/bar", "a+");
	if (fp == NULL)
	{
		fprintf(stderr, "test again: %s\n", strerror(errno));
	}

	return 0;
}


参考资料: 软件调试的艺术 P180

                    http://beej.us/guide/bgnet/output/html/multipage/perrorman.html

你可能感兴趣的:(File,null,FP)