Unexpected Return Value for fcntl and F_GETFL

222 Views Asked by At

Started with system calls in C.

Goal -> To get the opening modes of a file using fcntl

Code written ->

#include<stdio.h>
#include<fcntl.h>

int main()
{
    int fd , open_fl;
    if((fd =open("example.txt",O_RDWR ))<0){

        perror("program");
    }

     open_fl = fcntl(fd , F_GETFL );
     printf("%d file descriptor has %d flags.\n", fd , open_fl);

     return 0 ;
}

Getting Output ->

3 file descriptor has 32770 flags.

32770(decimal) -> 100002(octal)

But expected octal value is 2.

source fcntl.h code -> https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/fcntl.h

Why am i getting such an output difference?

1

There are 1 best solutions below

0
Hartmut Holzgraefe On

You are getting back o100002, which is a combination of the O_RDWR (o2) and O_LARGEFILE (o100000) flags.

The manpage for open() says:

O_LARGEFILE
       (LFS) Allow files whose sizes cannot be represented in an
       off_t (but can be represented in an off64_t) to be opened.
       The _LARGEFILE64_SOURCE macro must be defined (before
       including any header files) in order to obtain this
       definition.  Setting the _FILE_OFFSET_BITS feature test
       macro to 64 (rather than using O_LARGEFILE) is the
       preferred method of accessing large files on 32-bit
       systems (see feature_test_macros(7)).