我可以获取"FILE *"的访问方式吗? [英] Can I get the access mode of a `FILE*`?

查看:34
本文介绍了我可以获取"FILE *"的访问方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在Mac OS X上的C语言中复制一个 FILE * (不幸的是,毫无疑问,一直使用POSIX int 文件描述符),所以我提出了具有以下功能:

I have to duplicate a FILE* in C on Mac OS X (using POSIX int file descriptors all the way is unfortunately out of question), so I came up with the following function:

static FILE* fdup(FILE* fp, const char* mode)
{
    int fd = fileno(fp);
    int duplicated = dup(fd);
    return fdopen(duplicated, mode);
}

它工作得很好,除了它有一个丑陋的小部分,我再次要求文件模式,因为 fdopen 显然无法确定它本身.

It works very well, except it has that small ugly part where I ask for the file mode again, because fdopen apparently can't determine it itself.

此问题并不严重,因为基本上,我只是将其用于 stdin stdout stderr (显然,我了解这三种方式的访问方式).但是,如果我自己不知道的话,它会更优雅.这可能是可能的,因为 dup 调用不需要它.

This issue isn't critical, since basically, I'm just using it for stdin, stdout and stderr (and obviously I know the access modes of those three). However, it would be more elegant if I didn't have to know it myself; and this is probably possible since the dup call doesn't need it.

如何确定 FILE * 流的访问模式?

How can I determine the access mode of a FILE* stream?

推荐答案

您不能,但是您可以确定基础文件描述符的模式:

You can't, but you can determine the mode for the underlying file descriptor:

int fd = fileno(f);
int accmode = fcntl(fd, F_GETFL) & O_ACCMODE;

然后您可以根据 accmode O_RDONLY O_WRONLY 选择合适的模式传递给 fdopen O_RDWR .

You can then choose an appropriate mode to pass to fdopen based on whether accmode is O_RDONLY, O_WRONLY, or O_RDWR.

这篇关于我可以获取"FILE *"的访问方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆