我使用open()函数无法正确地打开/创建文件,所以我想使用errno消息来帮助我找出原因。然而,我不知道如何设置if()语句,以便它打印出错误信息。 我知道像这样的代码应该可以工作:
if(open(handle,O_RDWR | O_CREAT) == -1){
printf("%s\n",strerror(errno));
}
但是如果我想将open()的值保存到我的变量中,如果它是-1,则也打印错误怎么办?我不想为此调用两次open(),也不知道如何在它是ok的情况下进行分配,以及如何在不ok的情况下打印错误。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv){
int handle,i,help;
int *array = malloc(5*sizeof(int));
float *red = malloc(5*sizeof(int));
array[0]=5;
array[1]=4;
array[2]=3;
array[3]=2;
array[4]=1;
handle = open(argv[1], O_RDWR | O_CREAT);
if(handle == -1){
printf("%s\n",strerror(errno));
}
printf("handle 1 %d\n",handle);
write(handle,array,20);
close(handle);
handle = open(argv[1], O_RDONLY);
lseek(handle,0,SEEK_SET);
printf("handle %d\n",handle);
help=read(handle,&red,20);
printf("pomoc %d\n",help);
for(i=0; i<5; i++){
printf("%d\n",(int)red[i]);
}
close(handle);
return 0;
}