【问题标题】:write(): Bad file descriptorwrite():错误的文件描述符
【发布时间】:2015-05-20 01:16:27
【问题描述】:

我正在尝试学习 POSIX 中的基本 IO 函数,我编写了以下代码,但它不起作用,当我尝试执行代码时返回“Bad file descriptor”错误:

#include <stdio.h>
#include <stdlib.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(void)
{

    int nfd;
    ssize_t ret;

    mode_t mode = S_IRWXU | S_IRWXG;

    nfd = openat(AT_FDCWD, "idx.txt", O_APPEND | O_SYNC | O_CREAT, mode);

    if (-1 == nfd)
    {
        perror("openat()");
        exit(EXIT_FAILURE);
    }

    ret = write(nfd, "HELLO", 5);

    if (-1 == ret)
    {
        perror("write()");
        exit(EXIT_FAILURE);
    }

    close(nfd);

    return 0;
}

我想以 O_APPEND 模式写入文件。但是:

$ touch idx.txt # it does not work even if the file does not exist already
$ ./a.out
write(): Bad file descriptor

【问题讨论】:

标签: c posix file-descriptor


【解决方案1】:

您并没有告诉系统您要写入文件,将 O_WRONLY 或 O_RDWR 添加到标志使其工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    相关资源
    最近更新 更多