Search Suggest

Errors


Trong quá trình thực hiện các function, không phải lúc nào cũng thành công; một số các lỗi sẽ được liệt kê dưới đây thông qua mã lỗi errno nằm trong thư viện errono.h:
+ EPERM : Operation not permitted
+ ENOENT : No such file or directory
+ EINTR : Interrupted system call
+ EIO : I/O Error
+ EBUSY : Device or resource busy
+ EEXIST : File exists
+ EINVAL : Invalid argument
+ EMFILE : Too many open files
+ ENODEV : No such device
+ EISDIR : Is a directory
+ ENOTDIR : Isn’t a directory

Các hàm strerror và perror có mối liên hệ với giá trị của mã lỗi errno.

1. strerror
 #include <string.h>  
char *strerror(int errnum);

+ errnum
Mã lỗi, bằng giá trị errno.
+ return
Trả về string biểu diễn lý do lỗi.

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

In ra lỗi tương ứng với errno.
+ s
Chuỗi thông tin được in kèm với lỗi.

Ex:
error.c
 #include<stdio.h>  
#include<errno.h>
#include<string.h>

int main(void)
{
FILE *fd = NULL;

// Reset errno to zero before calling fopen().
errno = 0;

// Lets open a file that does not exist
fd = fopen("Linux.txt","r");
if(errno || (NULL == fd))
{
// Use strerror to display the error string

#if 1
perror("The function fopen failed due to");
#else
printf("The function fopen failed due to %s \n", strerror(errno));
#endif
return -1;
}

return 0;
}




Đăng nhận xét