[英]Error: Bad file descriptor, when open() a file
我想创建一个名称由用户输入的文件。
这是我的代码:
int function1(){
char path[50];
char choice_f;
char choice_m;
int flag; <-- updated
mode_t mode;
printf("Filename : ");
scanf("%s", path);
//printf("%s", path); <-- path can be shown
printf("\n");
printf("Desire flag : ");
scanf("%c", &choice_f); <-- updated
//printf("%s", path); <-- path CANNOT be shown from here
while (choice_f != '1' && choice_f != '2' && choice_f != '3'){
printf("Invalid input! Flag: ");
scanf("%c", &choice_f); <-- updated
}
if (choice_f == '1')
flag = O_RDONLY; <-- updated
else if (choice_f == '2')
flag = O_WRONLY; <-- updated
else if (choice_f == '3')
flag = O_RDWR; <-- updated
printf("Desire mode : ");
scanf("%c", &choice_m); <-- updated
while(choice_m != '1' && choice_m != '2' && choice_m != '3' && choice_m != '4'){
printf("Invalid input! Mode: ");
scanf("%c", &choice_m); <-- updated
}
if (choice_m == '1')
mode = S_IRWXU;
else if (choice_m == '2')
mode = S_IRWXG;
else if (choice_m == '3')
mode = S_IRWXO;
else if (choice_m == '4')
mode = S_IRWXU | S_IRWXG | S_IRWXO;
int fd = open(path, (int)flag|O_EXCL|O_CREAT);
fchmod(fd, mode);
printf("%d", fd);
if (fd == -1){
perror("error");
return 1;
}else
printf("File \'%s\' Created \n", path);
if (close(fd)<0)
perror("close()");
return 0;
}
但是在程序结束时,我收到错误消息:
Error: Bad file descriptor
我多次测试了path
,似乎在第二次scanf()
, path
无法显示。 即使我试图将path
分配给另一个变量,它仍然是一样的。
我应该怎么做才能解决这个错误?
我不确定这是否是唯一的问题,但您设置的 choice_f 和 choice_m 不正确,应该是
scanf("%c", &choice_f);
scanf("%c", &choice_m);
反而。 即您应该使用%c
格式说明符。 如果您使用%s
,则会写入一个 nul 终止符(至少); 您尚未为此提供存储空间,因此其他堆栈变量将被覆盖。
之后,正如 Nicholas Wilson 所建议的,您应该将flags
更改为int
而不是char*
(并从 O_RDONLY 等的赋值中删除引号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.