Can I get the access mode of a `FILE*`?

喜欢而已 提交于 2021-01-27 04:39:10

问题


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);
}

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.

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.

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


回答1:


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;

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



来源:https://stackoverflow.com/questions/13328864/can-i-get-the-access-mode-of-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!