9

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()?

Chostakovitch
  • 965
  • 1
  • 9
  • 33
rootkea
  • 1,474
  • 2
  • 12
  • 32

1 Answers1

7

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.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • Can't argue, can't verify if the need for `` and `` varies from system to system as I don't have another system to test. Can you give any one example of system needing these headers explicitly as I don't want to leave this to _may be possible_, _may be not_ – rootkea Feb 19 '15 at 14:51
  • 3
    @rootkea: Generally, things *do* vary. As KlasLindbäck said, the manpage specifies how to do it *portably*, and you should stick to it (because after all, it doesn't cost anything to have those extra includes if not needed; but your code won't compile, or worse, will invoke UB, if they *are* needed and you didn't include). – Tim Čas Feb 19 '15 at 14:53