令人尴尬的简单问题,但我似乎无法使用文件描述符打开新文件进行写入。我尝试过的每个变体都会返回 -1
。我错过了什么?这就是使用文件描述符初始化文件的方式,对吗?我找不到另有说明的文档。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
fd = open ("/home/CSTCIS/sample.dat", O_WRONLY, mode);
printf("%d\n", fd);
}
perror() 打印 open: No such file or directory
。
最佳答案
引用 pubs.opengroup.org ,
Upon successful completion, the [
open
] function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1.
要检查 open()
语句的问题,只需编写:
perror("open");
在 printf()
语句之前。
OP 找到了解决方案:
The
open()
command works ifO_CREAT
flag is included.fd = open ("/home/CSTCIS/sample.dat", O_WRONLY | O_CREAT, mode);
关于C 文件描述符在打开时返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159112/