C 文件描述符在打开时返回 -1

标签 c file-descriptor

令人尴尬的简单问题,但我似乎无法使用文件描述符打开新文件进行写入。我尝试过的每个变体都会返回 -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 if O_CREAT flag is included.

fd = open ("/home/CSTCIS/sample.dat", O_WRONLY | O_CREAT, mode);

关于C 文件描述符在打开时返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159112/

相关文章:

c - ld.exe : cannot find entry symbol _start

c - 在分配的内存范围之外写入时没有错误

c - 从小写到大写 : fatal errror

c - fwite/putc 是如何写入磁盘的?

bash - 奇怪的管道缓冲

c++ - 在更改文件描述符 1 以引用不同的文件后,我应该如何管理::std::cout?

c - Solaris 上的 'p' 的存储大小未知 (sys/procfs.h struct psinfo p) 错误

c++ - boost::process 系统泄漏文件描述符

linux - 打开文件过多错误,但 99.5% 的 inode 是免费的

c - 如何使用具有多个子进程的文件描述符的文件指针而不会在 C 中出现 "Bad file descriptor"错误?