2

How do I determine a user's OS in terminal application, in C? For example, in the code below, what should I replace windows and linux with?

/* pseudo code */
if(windows)
{system(cls)}
else if(linux)
{system(clear)}
else{...}

I should mention that I am a beginner at C, and need something like this so my code can work on windows and/or linux, without making separate source for each.

19greg96
  • 2,592
  • 5
  • 41
  • 55

3 Answers3

5

Typically, this is done with macros in the build system (since you have to BUILD the code for each system anyway.

e.g. gcc -DLINUX myfile.c

and then in myfile.c

 #ifdef LINUX
    ... do stuff for linux ... 
 #else if defined(WINDOWS)
    ... do something for windows ... 
 #else if ... and so on. 
    ... 
 #endif

(Most of the time, you can find some way that doesn't actually require the addition of a -D<something> on the command line, by using predefined macros for the tools you are using to compile for that architecture).

Alternatively, you ca do the same thing, but much quicker and better (but not 100% portable) by printing the ANSI escape sequence for "clear screen":

putstr("\033" "2J"); 

yes, that's two strings, because if you write "\0332J" the compile will use the character 0332, not character 033, followed by the digit 2. So two strings next to each other will do the trick.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

I believe you can avoid runtime check by specializing your 'functions' during compilation. So, how about this then:

#ifdef WIN32
   CLEAR = cls
#elif __linux__ 
   CLEAR = clear
#endif

Predefs vary from compiler to compiler, so here's a good list to have: http://sourceforge.net/p/predef/wiki/OperatingSystems/

nullpotent
  • 9,162
  • 1
  • 31
  • 42
0

It is probably better to detect the environment at compile time rather than runtime. With compiled languages like C you aren't going to have the same compiler output running on different platforms as you would with a lanugage such as Java so you don't need to do this kind of check at runtime.

This is the header I use to work out what platform my code is being compiled on. It will define different macros depending on the OS (as well as other things).

Something like this in use:

#if defined(UTIL_PLATFORM_WINDOWS)
    printf("windows\n");
#elif defined(UTIL_PLATFORM_UNIXLIKE)
    printf("Unix\n");
#endif
Will
  • 4,585
  • 1
  • 26
  • 48