%20%E8%BF%94%E5%9B%9E%E6%96%B0%E7%9A%84%E6%96%87%E4%BB%B6%E6%8F%8F%E8%BF%B0%E7%AC%A6%20posix%20.png)
我必须在 posix 中设置 open() 的返回值。如何返回“新文件描述符”,正如 Linux 手册页中所述:
返回值
open(), openat(), and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
编辑:谢谢金凤花!我没有看向正确的方向。我正在做的是纠正这个系统调用的返回值。显然它返回了错误的东西。
答案1
要打开文件,您可以使用如下结构:
int fd;
if ((fd = open(path, flags)) < 0) {
/* An error occurred, the reason is in errno */
int _errno = errno; /* Save errno value */
fprintf(stderr, "Failed opening file '%s': %s\n", path, strerror(_errno));
return;
}
/* The file was successfully opened */
因此,您只有一个返回值,通常是文件描述符。如果是-1
,则表明发生了错误。发生的错误存储在变量中(通过将其包含到源文件中来errno
获得)。errno.h