Thursday, July 30, 2009

How do you check which operating system a program is using when you are programming in the C language?

I want my C program to be able to check which OS it is being run in so that it can use the appropriate shell commands





Also, in C, what is the Linux equivalent for the C command





system("cls");





?








Thanks

How do you check which operating system a program is using when you are programming in the C language?
I am unaware of any universal way to determine the OS. That said, it really shouldn't be that much of an impediment.





Since you have to compile for each OS anyway, you can always use the time honored #define. E.G.





#define WINDOWS


....





#ifdef WINDOWS


string Clear("cls");


#else


string Clear("clear");


#endif


....





system(Clear);


=========





Or if you are solely focused on some kind of cls command, this should work on most platforms:





void clearScreen()


{


printf("\033[2J\033[1;1H");


}


===========





If the system is POSIX conforming, you can use uname. This should work fine on unix, linux, and OSX though I am unsure of Windows support for POSIX these days.





From linux:





#include %26lt;sys/utsname.h%26gt;





int uname(struct utsname *buf);


===================





Finally, if you are in a position to administer your systems, you can always just create an environment variable OS=Whatever and then access the environment via getenv() or the 3rd parameter to main().
Reply:In linux you can use system("clear") to clear the screen. In my experience the 'C' libraries have different calls depending upon the operating system (system v, linux, C etc). It can be done my adding a static text segment at link time detailing the operating system.





A command you can use on unix system is 'uname -a' which gives detailed os information.

sweet pea

No comments:

Post a Comment