#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> int main() { FILE* fp = fopen("test.txt","r"); if(fp == NULL) { fprintf(stderr,"error in open file test.txt,errno %s\n",strerror(errno));//strerror函数显示errno对应的具体错误 exit(-1); } return 0; }
读取文件并加入错误显示代码
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<errno.h> #include<fcntl.h> int readFromFile(const char* fileName,size_t length) { size_t bufferRead; char *buffer = (char *)malloc(length); if(buffer == NULL) { fprintf(stderr,"error in alloc memory buffer:%s\n",strerror(errno)); abort(); } int fd = open(fileName,O_RDONLY); if(fd == -1) { free(buffer); fprintf(stderr,"error in open file %s:%s\n",fileName,strerror(errno)); return -1; } while((bufferRead = read(fd,buffer,length)) != 0) { printf("%s\n",buffer); } close(fd); free(buffer); return 0; } int main() { readFromFile("test.txt",5); return 0; }