c - 使用 fcntl.h close 无法正确关闭文件

标签 c linux

这是下面的代码片段,我不确定为什么这不起作用

但是我得到的输出是

-1
-1

代码

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctime>

int main()
{

    int fd = open("/home/felipe/gdelt/fixed/test.bin", O_APPEND|O_WRONLY|O_CREAT);
    std::cout<<close(fd)<<std::endl;
    fd = open("/home/felipe/gdelt/fixed/test.bin", O_APPEND|O_WRONLY|O_CREAT);
    std::cout<<fd<<std::endl;
    //testWrite();
    return 0;
}

修改后的代码(添加模式使其工作)

int main()
{

    int fd = open("/home/felipe/gdelt/fixed/test.bin", O_APPEND|O_WRONLY|O_CREAT,S_IWUSR);
    std::cout<<close(fd)<<std::endl;
    fd = open("/home/felipe/gdelt/fixed/test.bin", O_APPEND|O_WRONLY|O_CREAT,S_IWUSR);
    std::cout<<fd<<std::endl;
    //testWrite();
    return 0;
}

最佳答案

来自 man 2 open 的一些引述。使用 O_CREAT 标志时,必须指定第三个 mode 参数。

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

mode specifies the permissions to use in case a new file is created. This argument must be supplied when O_CREAT is specified in flags; if O_CREAT is not specified, then mode is ignored.

首先是您的 open 系统调用失败了。 close 只是失败,因为您尝试在无效的文件描述符 -1 上使用它。

关于c - 使用 fcntl.h close 无法正确关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28331066/

相关文章:

c - 父进程收到信号后运行两次

linux - 如何在 Linux 下自动将给定的 so 加载到任何新启动的进程中?

PHP odbc 驱动程序作为共享扩展

mysql - 在 linux 环境下在 mysql 数据库中自动导入 csv

c - "resettable"带有 C 宏的循环 DSL?

c - 如何通过MPI加速这个问题

c - 我的第一个 C 语言代码卡住了,我无法创建可执行文件?

regex - 如何从文件中 grep 精确匹配特殊字符?

python - 在 Python 中将实时标准输出记录到文件中?

c - 从没有 fileno() 的文件指针获取文件描述符