C File Operations: Check opened file pointer access mode

前端 未结 3 1467
慢半拍i
慢半拍i 2021-01-18 14:40

A simple question:

How do I check the access mode of an already opened file pointer?

So say a function is passed an already opened FILE pointer:



        
相关标签:
3条回答
  • 2021-01-18 15:18

    Warning: this answer is specific to Visual Studio 2010.


    The stdio.h file that comes with Visual Studio 2010 defines the FILE type like this:

    struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
    };
    typedef struct _iobuf FILE;
    

    When fopening a file with the "rb" mode, it gets the value of 0x00000001.

    In the fopen function, some of the flags you're interesed in can be mapped as this:

    r    _IOREAD
    w    _IOWRT
    a    _IOWRT
    +    _IORW
    

    These constants are defined in stdio.h:

    #define _IOREAD         0x0001
    #define _IOWRT          0x0002
    #define _IORW           0x0080
    

    The underlying file descriptor contains more info, I haven't dug further yet.

    0 讨论(0)
  • 2021-01-18 15:34

    There is no standard way to achieve that.

    0 讨论(0)
  • 2021-01-18 15:40

    On Linux (and possibly all UNIX systems) you could use fcntl to get the access mode of the file:

    int get_file_status(FILE* f) {
        int fd = fileno(f);
        return fcntl(fd, F_GETFL);
    }
    

    Note that the returned value is an integer as combination of flags like O_RDONLY or O_RDWR, not the "r" or "w+" strings. See http://pubs.opengroup.org/onlinepubs/007908799/xsh/open.html for some of these flags.

    Not sure about Windows, see On Windows/mingw, what is the equivalent of `fcntl(fd, F_GETFL) | O_ACCMODE`?.

    0 讨论(0)
提交回复
热议问题