gpt4 book ai didi

c - 如何在保存函数值的同时打印 errno?

转载 作者:行者123 更新时间:2023-12-02 01:14:02 28 4
gpt4 key购买 nike

我无法使用 open() 函数正确打开/创建文件,所以我认为使用 errno 消息将帮助我找出原因。但是我不知道如何设置 if(),所以它会打印错误。
我知道这样的代码应该可以工作:

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;
}

最佳答案

问题不在于分配给变量,而是您调用 open 的方式:

handle = open(argv[1], O_RDWR|O_CREAT); // wrong number of arguments
if (handle == -1) {
printf("%s\n",strerror(errno));
}

当您使用 O_CREAT , 你必须给 open三个论点。如果不这样做,则行为未定义。偶然地,当你有 open 时,你得到了一个 -1 错误返回。调用 if ,以及将其分配给变量时的非负返回值。

除非您有具体的理由不这样做,否则 open 的第三个参数应该是魔数(Magic Number) 0666 . (不这样做的最常见的具体原因是您正在创建一个将保存 secret 信息的文件;然后您使用 0600 。)(前导零是必需的。)有可用于第三个参数的符号常量至 open但是,一旦您知道数字“模式”的含义,符号常量实际上就更难阅读了。 Here is a detailed explanation of "modes" in both symbolic and numeric forms.

顺便说一句,当系统调用失败时,您应该始终打印 strerror(errno)以及违规文件的名称(如果有):
handle = open(argv[1], O_RDWR|O_CREAT, 0666);
if (handle == -1) {
printf("%s: %s\n", argv[1], strerror(errno));
exit(1);
}

您应该考虑是否应该使用 O_EXCLO_TRUNC .

关于c - 如何在保存函数值的同时打印 errno?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559792/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com