Discover machine operating system in C

Asked

Viewed 1,366 times

5

I need to do a function to clean the C screen running on Windows, Mac and Linux. I thought to do a function that:

If the OS were Windows: system("cls");

If the OS was Linux or Mac: system("clear");

The problem is: How do I discover the computer’s operating system and how would these if and else?

  • 1

    Have a look http://nadeausoftware.com/articles/2012/01/c_tip_how_use_compiler_predefined_macros_detect_operating_system

  • I think you better create a program for each OS. If you are going to do everything together, it will get heavier and confusing.

2 answers

5


To know if the system is linux or windows can do as follows:

#ifdef __unix__         
    #include <unistd.h>
    #include <stdlib.h>

#elif defined(_WIN32) || defined(WIN32) 

   #define OS_Windows

   #include <windows.h>

#endif

int main(int argc, char *argv[]) 
{
#ifdef OS_Windows
 /* Codigo Windows */
    system("cls");
#else
 /* Codigo GNU/Linux */
    system("clear");
#endif    
}

4

In this answer, I used this:

#if defined(__MINGW32__) || defined(_MSC_VER)
#define limpar_input() fflush(stdin)
#define limpar_tela() system("cls")
#else
#include <stdio_ext.h>
#define limpar_input() __fpurge(stdin)
#define limpar_tela() system("clear")
#endif
  • I usually look for the definition of WIN32 or _WIN32. I also use Visual Studio more than MingW to program

Browser other questions tagged

You are not signed in. Login or sign up in order to post.