[英]Bad file descriptor
我正在學習文件描述符,並編寫了以下代碼:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int fdrd, fdwr, fdwt;
char c;
main (int argc, char *argv[]) {
if((fdwt = open("output", O_CREAT, 0777)) == -1) {
perror("Error opening the file:");
exit(1);
}
char c = 'x';
if(write(fdwt, &c, 1) == -1) {
perror("Error writing the file:");
}
close(fdwt);
exit(0);
}
,但我得到: Error writing the file:: Bad file descriptor
我不知道可能出了什么問題,因為這是一個非常簡單的示例。
嘗試這個:
open("output", O_CREAT|O_WRONLY, 0777)
我認為僅O_CREAT
是不夠的。 嘗試將O_WRONLY
作為標志添加到打開命令中。
根據 open(2) 手冊頁:
參數標志必須包括以下訪問模式之一:O_RDONLY、O_WRONLY 或 O_RDWR。
所以是的,按照其他人的建議,請將您的open
更改為open("output", O_CREAT|O_WRONLY, 0777));
. 如果需要從文件中讀取,請使用O_RDWR
。 您可能還需要O_TRUNC
- 有關詳細信息,請參閱手冊頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.