C File Operations: Check opened file pointer access mode

前端 未结 3 1469
慢半拍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: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`?.

提交回复
热议问题