[英]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.