Determine OS during runtime

半城伤御伤魂 提交于 2019-12-05 05:35:35

Actually, most systems have a uname command which shows the current kernel in use. On Mac OS, this is usually "Darwin", on Linux it's just plain "Linux", on Windows it's "ERROR" and FreeBSD will return "FreeBSD".

More complete list of uname outputs

I'm pretty sure that there's a C equivalent for uname, so you won't need system()

IF you are on a POSIX system, you can call uname() from <sys/utsname.h>.

This obviously isn't 100% portable, but I don't think there will be any method that can grant that at runtime.

see the man page for details

Runtime isn't the time to determine this, being that without epic kludges binaries for one platform won't run on another, you should just use #ifdefs around the platform sensitive code.

The accepted answer states uname, but doesn't provide a minimal working example, so here it is for anyone interested-hope it will save you the time it took for me:

#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>

int main(void) {
   struct utsname buffer;
   if (uname(&buffer) != 0) {
      perror("uname");
      exit(0);
   }
   printf("OS: %s\n", buffer.sysname);

   return 0;
}

(Possible) Output:

OS: Linux

PS: Unfortunately, this uses a POSIX header: Compilation fails due to missing file sys/utsname.h, which most probably won't work in Windows.

Roberto Cabellon
if (strchr(getenv("PATH"),'\\'))
    puts("You may be on windows...");

Even do I agree that "Runtime isn't the time to determine this..."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!