Why include direct.h or sys/stat.h conditionally based on _WIN32 or __linux__?

Bosnia picture Bosnia · Aug 13, 2014 · Viewed 9k times · Source

What will the following code do? Why is it used?

  #ifdef _WIN32
  #include <direct.h>
  #elif defined __linux__
  #include <sys/stat.h>
  #endif

Answer

Mohit Jain picture Mohit Jain · Aug 13, 2014

There is no portable way in C to manipulate file system directories. You need some library that provides wrapper interfaces to manipulate directories. (Using system call, OS interrupts routines etc)

direct.h is a header file for the C programming language for windows. It contains declaration of functions and required macros, struct etc used to manipulate file system directories. In Linux like system, you can use sys/stat.h for the same.

Now if your code may be compiled for either of the OS, you can keep the common (portable) code without any guards and keep windows-specific or linux-specific code in conditional compilation block.

If you don't include those files conditionally, you may get direct.h not found or similar error in Linux and any similar error for windows.

__linux__ is pre-defined by the compiler targeting the code for Linux.

This msdn document says:

_WIN32: Defined for applications for Win32 and Win64. Always defined.