open() system call header file requirements

rootkea picture rootkea · Feb 19, 2015 · Viewed 13.5k times · Source

I am using x86_64 GNU/Linux with gcc.
SYNOPSIS section of man -s2 open says:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);

Now when I try to compile the following code snippet, gcc doesn't throw a warning/error.

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

int main(int argc, char **argv)
{
    int fd;

    fd = open("foo.txt", O_RDWR, 0777);
    if(fd == -1)
        perror("open");

    fd = creat("foo.txt", 0777);
    if(fd == -1)
        perror("creat");

    close(fd);
    return 0;
}

So are types.h and stat.h optional? What purpose do they serve in manpage of open()?

Answer

Klas Lindb&#228;ck picture Klas Lindbäck · Feb 19, 2015

The man page serves as an instruction both to programmers and to compiler manufacturers.

It is possible that you don't need to include them on your system. However, the man page describes a portable way to use the methods, so you should include them anyway.