用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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章