我无法使用open()函数正确打开/创建文件,所以我认为使用errno消息将帮助我找出原因。但是我不知道如何设置if(),所以它会打印出错误信息。 我知道这样的代码应该工作:如何在保存函数值的同时打印errno?
if(open(handle,O_RDWR | O_CREAT) == -1){
printf("%s\n",strerror(errno));
}
但如果我想保存从open()来我的变量的值,如果是-1,那么打印错误呢?我不想为此调用open()两次,如果没有问题,我不知道如何分配它,以及如果没有,则如何打印错误。
#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;
}
这是我的“尝试”代码,因为我不确定read()函数是如何工作的,所以我想试试如果我可以在那里抛出任何类型的指针并读取任意数量的字节,并且它可以工作,但是我甚至无法通过开幕式。 – ligazetom
请注意,在报告错误之后,您不应继续处理,因为如果处理已打开。错误应该在标准错误流上报告,而不是在标准输出上报告。 –