小编abb*_*123的帖子

write(): 错误的文件描述符

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

$ touch idx.txt # it does not work even if the file does not …
Run Code Online (Sandbox Code Playgroud)

c posix file-descriptor

3
推荐指数
1
解决办法
2864
查看次数

标签 统计

c ×1

file-descriptor ×1

posix ×1