strerror和perror函数示例

/*#include <string.h>

char *strerror(int errnum);

它返回errnum的值所对应的错误提示信息,例如errnum等于12的话,它就会返回"Cannot allocate memory"。

测试程序:*/

#include <stdio.h>

#include <string.h>

#include <errno.h>



int main(void)

{

    int fd = 10;

    int ret;

    ret = close(fd);

    if(ret == -1)

 //fprintf(stderr, "close error with msg is: %s\n",strerror(errno));这两行输出的结果都是一样的

  printf("close error with msg is: %s\n",strerror(errno));

    return 0;

}



#include <stdio.h>

#include <string.h>

#include <errno.h>

#include<stdlib.h>

int main(void)

{ extern int errno;

 int fd = 10;

 int ret;

 ret = close(fd);

 if(ret == -1)

  printf("errno=%d\n",errno);

  char * mesg = strerror(errno);

  printf("Mesg:%s\n",mesg);

  exit(0);

}

/*[root@linux untitled folder 2]# gcc strerror1.c

[root@linux untitled folder 2]# ./a.out

errno=9

Mesg:Bad file descriptor

[root@linux untitled folder 2]# 

*/


#include <stdio.h>

int main(void)

{

    int fd = 10;

    int ret;

    ret = close(fd);

    if(ret == -1)

        perror("close error");

    return 0;

}

/*[root@linux untitled folder 2]# gcc perror.c

[root@linux untitled folder 2]# ./a.out

close error: Bad file descriptor*/

//函数原型为void perror(const char *s);
 

 

你可能感兴趣的:(error)