Luc*_*ucy 19 c unix file 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);
}
Run Code Online (Sandbox Code Playgroud)
,但我得到了: Error writing the file:: Bad file descriptor
我不知道会出现什么问题,因为这是一个非常简单的例子.
小智 21
试试这个:
open("output", O_CREAT|O_WRONLY, 0777)
Run Code Online (Sandbox Code Playgroud)
根据open(2)手册页:
参数标志必须包括以下访问模式之一:O_RDONLY,O_WRONLY或O_RDWR.
是的,正如其他人所建议的那样,请改变你open的意见open("output", O_CREAT|O_WRONLY, 0777));.O_RDWR如果需要从文件中读取,请使用.您可能还需要O_TRUNC- 有关详细信息,请参见手册页.