C 标准错误处理函数 fprintf 和 printf

在源代码中经常会出现下面一些错误处理函数。

一、errno

头文件:#include <errno.h>

函数原型:errno

功能:记录系统的最后一次错误代码

参数:无

返回值:错误代号(整型值)

例子

1
2
3
4
5
  if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        fprintf(stderr, "errno = %d \n", errno);
        exit(1);
    }
printf("Socket opened successfully \n");
//errno 返回整型错误代号。

二、strerror   strerror_r

头文件:#include <string.h>

函数原型

char *strerror(int errnum);

char *_strerror(const char *strErrMsg);

wchar_t * _wcserror(int errnum);

wchar_t * __wcserror(const wchar_t *strErrMsg);

参数:errnum——错误代码,strErrMsg——用户提供的信息。

返回值:指向错误信息的指针。

1
2
3
4
5
      if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        fprintf(stderr, "errno = %d \n", errno);
        fprintf(stderr, "Error description is : %s\n",strerror(errno));
        exit(1);
    } 
    //strerror(errno)返回指向errno对应的错误信息的指针,即第三个fprintf输出的是错误信息描述。

三、perror

头文件

#include<stdio.h>  

#include<stdlib.h>

函数原型

void perror(const char *s);

perror ("open_port");

函数功能

perror ( )用 来 将 上 一 个 函 数 发 生 错 误 的 原 因 输 出 到 标 准 设备 (stderr) 。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量errno 的值来决定要输出的字符串。

在库函数中有个errno变量,每个errno值对应着以字符串表示的错误类型。当你调用"某些"函数出错时,该函数已经重新设置了errno的值。perror函数只是将你输入的一些信息和现在的errno所对应的错误一起输出。

参数:用户输入的字符串

返回值:无

例子

1
2
3
4
5
6
7
8
      if(( sockfd = socket(AF_INET,SOCK_DGRAM,0))<0)
    {
        perror("myError");
        exit(1);
    } else 
    {
        printf("socket created successfully!\n");
    }
    //先打印出字符串myError(即perror的参数),再打印errno对应的错误信息。
    //打印到标准设备上,stderr即对应终端的屏幕。

四、fprintf和printf

#include <stdio.h>

 

int fprintf(FILE *stream,const char *format,…);

根据format格式发送参数到stream流。

 

int printf(const char *format,…);

通过标准输出设备输出一组数据。

posted @ 2012-09-11 20:13  helloweworld  阅读(1651)  评论(0编辑  收藏  举报