这是下面的代码片段,我不确定为什么这不起作用
但是我得到的输出是
-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/