C File Operations: checking the access mode of an open file

Simple question:

How to check the access mode to an already open file pointer?

So to say, the function is passed by the already open FILE pointer:

    //Pseudo code
    bool PseudoFunction(FILE *Ptr)
    {
        if( ... Insert check for read-only access rights )
        {
            //It read only access mode
            return true;
        }
       //File pointer is not read-only and thus write operations are permitted
       return false;
    }

What would I use in an if statement to test a FILE pointer, be open as read-only (or, as the case may be), without writing to a file and not relying on a user passing (possibly conflicting) arguments?

The system is a windows, code :: blocks compiler, but cross-compatibility is preferred for code portability interests.

Note that this does not ask about file permissions, but what access mode was used by the FILE pointer.

SELF-ANSWER [Unable to add a separate response due to user rights restrictions]:

, #defines

, , FILE _flag ( _iobuf) , . , , , , :

#define READ_ONLY_FLAG 1

bool PrintFlagPtr(const char FileName[], const char AccessMode[])
{
    FILE *Ptr = NULL;
    Ptr = fopen(FileName,AccessMode);
    printf("%s: %d ",AccessMode,Ptr->_flag);

    int IsReadOnly = Ptr->_flag;
    fclose(Ptr);
    Ptr = NULL;


    if( (IsReadOnly&READ_ONLY_FLAG) == READ_ONLY_FLAG )
    {
        printf("File is read only!\n");
        return true;
    }

    printf("\n");
    return false;
}

, , :

Output:
w: 2
r: 1 File is read only!
a: 2
wb: 2
rb: 1 File is read only!
ab: 2
w+: 128
r+: 128
a+: 128
w+b: 128
r+b: 128
a+b: 128

, ( ), - front-end ( , , ), const int, FILE _flag .

+5
3

: Visual Studio 2010.


stdio.h, Visual Studio 2010, FILE :

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

"rb" 0x00000001.

fopen , , :

r    _IOREAD
w    _IOWRT
a    _IOWRT
+    _IORW

stdio.h:

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

, .

+2

Linux (, , UNIX-) fcntl :

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

, , O_RDONLY O_RDWR, "r" "w+". . http://pubs.opengroup.org/onlinepubs/007908799/xsh/open.html .

Windows, . Windows/mingw, ` fcntl (fd, F_GETFL) | O_ACCMODE`?.

+3

There is no standard way to achieve this.

+1
source

All Articles