perror()函数的运用(详解)

1、作用:
打印系统错误信息

2、原型

#include <stdio.h>
void perror(const char *s);
#include <errno.h>

3、代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
        int fd;
        fd=open("./file", O_RDWR);//打开文件file,读写方式
		if(fd < 0){
			printf("open failure\n");
			perror("why");//打印失败的原因
		}
        close(fd);
        return 0;
}

运行结果:
//我的目录下是没有文件file的

open failure
why: No such file or directory

4、描述
(1)例程perror()在标准错误输出上生成一条消息,描述在调用系统或库函数时遇到的最后一个错误。首先(如果s不是NULL并且*s不是NULL字节(’\0’))将输出参数字符串s,后跟一个冒号和一个空白。然后是消息和新一行。
(2)最常用的是,参数字符串应该包括导致错误的函数的名称。错误号来自外部变量errno,该变量在发生错误时设置,但在成功调用时不清除。
(3)可以使用errno索引的全局错误列表sys_errlist[]获取不换行的错误消息。表中提供的最大消息数是sys_nerr 1。当直接访问这个列表时要小心,因为新的错误值可能没有被添sys_errlist[]。
(4)当系统调用失败时,它通常返回1,并将变量errno设置为描述出错原因的值。(这些值可以在<errno.h>中找到。)许多库函数也是这样做的。函数perror()将错误代码转换为人类可读的形式。注意,在成功的库调用之后,errno是未定义的:这个调用很可能更改这个变量,即使它成功了,例如,因为它在内部使用了其他失败的库函数。因此,如果失败的调用之后没有立即调用perror(),则应该保存errno的值。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C函数库手册,按照函数功能来分类 分类函数,所在函数库为ctype.h int isalpha(int ch) 若ch 是字母('A'-'Z','a'-'z')返回非0 值,否则返回0 int isalnum(int ch) 若ch 是字母('A'-'Z','a'-'z')或数字('0'-'9')返回非0 值,否则返回0 ...... 数学函数,所在函数库为math.h、stdlib.h、string.h、float.h int abs(int i) 返回整型参数i 的绝对值 double cabs(struct complex znum) 返回复数znum 的绝对值 double fabs(double x) 返回双精度参数x 的绝对值 ...... 目录函数,所在函数库为dir.h、dos.h int chdir(char *path) 使指定的目录path(如:"C:\\WPS")变成当前的工作目录,成 功返回0 int findfirst(char *pathname,struct ffblk *ffblk,int attrib)查找指定的文件,成功 返回0 ...... 进程函数,所在函数库为stdlib.h、process.h void abort() 此函数通过调用具有出口代码3 的_exit 写一个终止信息于stderr,并异常终止程序。无返回值 int exec…装入和运行其它程序 ...... 转换子程序,函数库为math.h、stdlib.h、ctype.h、float.h char *ecvt(double value,int ndigit,int *decpt,int *sign)将浮点数value 转换成字符串并返回该字符串 char *fcvt(double value,int ndigit,int *decpt,int *sign)将浮点数value 转换成字符串并返回该字符串 ...... 诊断函数,所在函数库为assert.h、math.h void assert(int test) 一个扩展成if 语句那样的宏,如果test 测试失败,就显示一个信息并异常终止程序,无返回值 void perror(char *string) 本函数将显示最近一次的错误信息,格式如下:字符串string:错误信息 ...... 输入输出子程序,函数库为io.h、conio.h、stat.h、dos.h、stdio.h、signal.h int kbhit() 本函数返回最近所敲的按键 int fgetchar() 从控制台(键盘)读一个字符,显示在屏幕上 ...... 接口子程序,所在函数库为:dos.h、bios.h unsigned sleep(unsigned seconds)暂停seconds 微秒(百分之一秒) int unlink(char *filename)删除文件filename unsigned FP_OFF(void far *farptr)本函数用来取远指针farptr 的偏移量 ...... 存贮分配子程序,所在函数库为dos.h、alloc.h、malloc.h、stdlib.h、process.h int allocmem(unsigned size,unsigned *seg)利用DOS 分配空闲的内存,size 为分配内存大小,seg 为分配后的内存指针 int freemem(unsigned seg)释放先前由allocmem 分配的内存,seg 为指定的内存指针 ...... 操作函数,所在函数库为string.h、mem.h mem…操作存贮数组 ...... ......
C语言函数及相关知识 函数名: abort 功 能: 异常终止一个进程 用 法: void abort(void); 程序例: #include <stdio.h> #include <stdlib.h> int main(void) { printf("Calling abort()\n"); abort(); return 0; /* This is never reached */ } 函数名: abs 功 能: 求整数的绝对值 用 法: int abs(int i); 程序例: #include <stdio.h> #include <math.h> int main(void) { int number = -1234; printf("number: %d absolute value: %d\n", number, abs(number)); return 0; } 函数名: absread, abswirte 功 能: 绝对磁盘扇区读、写数据 用 法: int absread(int drive, int nsects, int sectno, void *buffer); int abswrite(int drive, int nsects, in tsectno, void *buffer); 程序例: /* absread example */ #include <stdio.h> #include <conio.h> #include <process.h> #include <dos.h> int main(void) { int i, strt, ch_out, sector; char buf[512]; printf("Insert a diskette into drive A and press any key\n"); getch(); sector = 0; if (absread(0, 1, sector, &buf) != 0) { perror("Disk problem"); exit(1); } printf("Read OK\n"); strt = 3; for (i=0; i<80; i++) { ch_out = buf[strt+i]; putchar(ch_out); } printf("\n"); return(0); } 函数名: access 功 能: 确定文件的访问权限 用 法: int access(const char *filename, int amode); 程序例: #include <stdio.h> #include <io.h> int file_exists(char *filename); int main(void) { printf("Does NOTEXIST.FIL exist: %s\n", file_exists("NOTEXISTS.FIL") ? "YES" : "NO"); return 0; } int file_exists(char *filename) { return (access(filename, 0) == 0); } 函数名: acos 功 能: 反余弦函数 用 法: double acos(double x); 程序例: #include <stdio.h> #include <math.h> int main(void) { double result; double x = 0.5; result = acos(x); printf("The arc cosine of %lf is %lf\n", x, result); return 0; } 函数名: allocmem 功 能: 分配DOS存储段 用 法: int allocmem(unsigned size, unsigned *seg); 程序例: #include <dos.h> #include <alloc.h> #include <stdio.h> int main(void) { unsigned int size, segp; int stat; size = 64; /* (64 x 16) = 1024 bytes */ stat = allocmem(size, &segp); if (stat == -1) printf("Allocated memory at segment: %x\n", segp); else printf("Failed: maximum number of paragraphs available is %u\n", stat); return 0; } 函数名: arc 功 能: 画一弧线 用 法: void far arc(int x, int y, int stangle, int endangle, int radius); 程序例: #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 45, endangle = 135; int radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw arc */ arc(midx, midy, stangle, endangle, radius); /* clean up */ getch(); closegraph(); return 0; } 函数名: asctime 功 能: 转换日期和时间为ASCII码 用 法: char *asctime(const struct tm *tblock); 程序例: #include <stdio.h> #include <string.h> #include <time.h> int main(void) { struct tm t; char str[80]; /* sample loading of tm structure */ t.tm_sec = 1; /* Seconds */ t.tm_min = 30; /* Minutes */ t.tm_hour = 9; /* Hour */ t.tm_mday = 22; /* Day of the Month */ t.tm_mon = 11; /* Month */ t.tm_year = 56; /* Year - does not include century */ t.tm_wday = 4; /* Day of the week */ t.tm_yday = 0; /* Does not show in asctime */ t.tm_isdst = 0; /* Is Daylight SavTime; does not show in asctime */ /* converts structure to null terminated string */ strcpy(str, asctime(&t)); printf("%s\n", str); return 0; } 函数名: asin 功 能: 反正弦函数 用 法: double asin(double x); 程序例: #include <stdio.h> #include <math.h> int main(void) { double result; double x = 0.5; result = asin(x); printf("The arc sin of %lf is %lf\n", x, result); return(0); } 函数名: assert 功 能: 测试一个条件并可能使程序终止 用 法: void assert(int test); 程序例: #include <assert.h> #include <stdio.h> #include <stdlib.h> struct ITEM { int key; int value; }; /* add item to list, make sure list is not null */ void additem(struct ITEM *itemptr) { assert(itemptr != NULL); /* add item to list */ } int main(void) { additem(NULL); return 0; } 函数名: atan 功 能: 反正切函数 用 法: double atan(double x); 程序例: #include <stdio.h> #include <math.h> int main(void) { double result; double x = 0.5; result = atan(x); printf("The arc tangent of %lf is %lf\n", x, result); return(0); } 函数名: atan2 功 能: 计算Y/X的反正切值 用 法: double atan2(double y, double x); 程序例: #include <stdio.h> #include <math.h> int main(void) { double result; double x = 90.0, y = 45.0; result = atan2(y, x); printf("The arc tangent ratio of %lf is %lf\n", (y / x), result); return 0; } 函数名: atexit 功 能: 注册终止函数 用 法: int atexit(atexit_t func); 程序例: #include <stdio.h> #include <stdlib.h> void exit_fn1(void) { printf("Exit function #1 called\n"); } void exit_fn2(void) { printf("Exit function #2 called\n"); } int main(void) { /* post exit function #1 */ atexit(exit_fn1); /* post exit function #2 */ atexit(exit_fn2); return 0; } 函数名: atof 功 能: 把字符串转换成浮点数 用 法: double atof(const char *nptr); 程序例: #include <stdlib.h> #include <stdio.h> int main(void) { float f; char *str = "12345.67"; f = atof(str); printf("string = %s float = %f\n", str, f); return 0; } 函数名: atoi 功 能: 把字符串转换成长整型数 用 法: int atoi(const char *nptr); 程序例: #include <stdlib.h> #include <stdio.h> int main(void) { int n; char *str = "12345.67"; n = atoi(str); printf("string = %s integer = %d\n", str, n); return 0; } 函数名: atol 功 能: 把字符串转换成长整型数 用 法: long atol(const char *nptr); 程序例: #include <stdlib.h> #include <stdio.h> int main(void) { long l; char *str = "98765432"; l = atol(lstr); printf("string = %s integer = %ld\n", str, l); return(0); }
`recvfrom` 函数用于接收一个来自指定套接字的数据报,并将发送方的地址和端口号存储在指定的缓冲区中。 函数原型如下: ```c #include <sys/socket.h> ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); ``` 参数说明: - `sockfd`:指定接收数据的套接字文件描述符。 - `buf`:指向接收缓冲区的指针。 - `len`:指定接收缓冲区的大小。 - `flags`:指定接收操作的标志位,通常设置为 0。 - `src_addr`:指向发送方地址信息的结构体指针。 - `addrlen`:指向发送方地址信息结构体长度的指针。 函数的返回值为接收到的字节数,如果出现错误则返回 -1。 注意事项: - 如果套接字是非阻塞的,则 `recvfrom` 函数可能会返回 -1 并设置 `errno` 为 `EAGAIN` 或 `EWOULDBLOCK`。 - 如果接收缓冲区中的数据长度大于 `len`,则数据将被截断。 - `src_addr` 和 `addrlen` 参数可以设置为 `NULL`,表示不关心发送方地址信息。 示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8080 #define BUFFER_SIZE 1024 int main() { int sockfd; struct sockaddr_in server_addr, client_addr; socklen_t client_addrlen = sizeof(client_addr); char buffer[BUFFER_SIZE]; // 创建套接字 if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } // 绑定地址 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(PORT); if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // 接收数据 ssize_t num_bytes; while (1) { memset(buffer, 0, BUFFER_SIZE); num_bytes = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &client_addrlen); if (num_bytes < 0) { perror("recvfrom failed"); exit(EXIT_FAILURE); } printf("Received message from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); printf("Data: %s\n", buffer); } close(sockfd); return 0; } ``` 该示例代码创建一个 UDP 服务器,不断接收发送方发送的数据,并输出发送方的地址信息和数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值