operating-systemruntime

Determining an operating system at runtime?


I was on the irc.quakenet.org #cplusplus channel, and some of the developers got to talking, and started to try and think up a way to determine the current operating system at runtime. We are aware of how to do it at compile time quite easily and that it wouldn't make sense to do it at runtime, but we just wanted a challenge. So far, we have yet to come up with a surefire way of doing this during runtime. Does anyone know of any solution/hack/trick/etc that would allow this?


Solution

  • It would have to be a combination of compile time and runtime logic.

    char *get_os_name (void);
    
    #ifdef _LINUX
        char *get_os_name (void)
        {
             static nm [1000];
             FILE *f = fopen ("/proc/version", "r");
             if (!f  &&  !fgets (nm, sizeof nm, f))
                   return NULL;  /* could next try uname(), etc. */
             fclose (f);
             return nm;
        }
    #endif
    
    #ifdef _WIN32
        char *get_os_name (void)
        {
             OSVERSIONINFO   vi;
    
             memset (&vi, 0, sizeof vi);
             vi .dwOSVersionInfoSize = sizeof vi;
             GetVersionEx (&vi);
             switch (vi.dwPlatformId)
             {
             case VER_PLATFORM_WIN32_NT:  return "Win32";
             ...
             }
        }
    #endif