C File Operations: Check opened file pointer access mode

前端 未结 3 1494
慢半拍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.

提交回复
热议问题