从FILE结构获取文件模式? [英] Getting the file-mode from the FILE struct?

查看:94
本文介绍了从FILE结构获取文件模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C代码,一个具体的函数,它对 FILE * 起作用。



取决于 FILE * 打开的模式,有一些我可以做和不能做的事情。



是否有任何方式我可以获得 FILE * 以打开方式?



FILE * 是所有我可以信赖的信息,因为它是在程序中的其他地方创建的,实际的文件名在它到达我的函数之前就已经丢失了,这不能影响。 / p>

我想要一个可移植的解决方案。



编辑:我不感兴趣的文件限制指定哪些用户可以做什么与文件。这是大多数不相关的,因为它是在文件打开时处理。

解决方案

在POSIX(足够相似)的系统上, fcntl(fileno(f),F_GETFL)将返回打开文件的模式/标志,形式将传递到 open (不是 fopen )。要检查它是否以只读,读写或只写方式打开,可以执行以下操作:

  int mode = fcntl(fileno(f),F_GETFL); 
switch(mode& O_ACCMODE){
case O_RDONLY:...
case O_WRONLY:...
case O_RDWR:...
}

您还可以检查 O_APPEND 等标志


I have a piece of C code, a function to be specific, which operates on a FILE*.

Depending on which mode the FILE* was opened with there are certain things I can and cannot do.

Is there any way I can obtain the mode the FILE* was opened with?

That FILE* is all the info I can rely on, because it is created somewhere else in the program and the actual file-name is long lost before it reaches my function, and this I cannot influence.

I would prefer a portable solution.

Edit: I'm not interested in file-restrictions specifying which users can do what with the file. That is mostly irrelevant as it is dealt with upon file-opening. For this bit of code I only care about the open-mode.

解决方案

On POSIX (and sufficiently similar) systems, fcntl(fileno(f), F_GETFL) will return the mode/flags for the open file in the form that would be passed to open (not fopen). To check whether it was opened read-only, read-write, or write-only, you can do something like:

int mode = fcntl(fileno(f), F_GETFL);
switch (mode & O_ACCMODE) {
case O_RDONLY: ...
case O_WRONLY: ...
case O_RDWR: ...
}

You can also check for flags like O_APPEND, etc.

这篇关于从FILE结构获取文件模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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