Getting the OS version in Mac OS X using standard C

前端 未结 3 1597
遇见更好的自我
遇见更好的自我 2020-12-18 20:03

I\'m trying to get the version of Mac OS X programmatically in C. After searching for a while I tried this code:

#include 

        
3条回答
  •  伪装坚强ぢ
    2020-12-18 20:53

    Here is one with "less work", good enough for home projects (statically allocated buffers, ignoring errors). Works for me in OS X 10.11.1.

    #include 
    
    /*!
      @brief    Returns one component of the OS version
      @param    component  1=major, 2=minor, 3=bugfix
     */
    int GetOSVersionComponent(int component) {
        char cmd[64] ;
        sprintf(
                cmd,
                "sw_vers -productVersion | awk -F '.' '{print $%d}'",
                component
        ) ;
        FILE* stdoutFile = popen(cmd, "r") ;
    
        int answer = 0 ;
        if (stdoutFile) {
            char buff[16] ;
            char *stdout = fgets(buff, sizeof(buff), stdoutFile) ;
            pclose(stdoutFile) ;
            sscanf(stdout, "%d", &answer) ;
        }
    
        return answer ;
    }
    
    int main(int argc, const char * argv[]) {
        printf(
               "Your OS version is: %d.%d.%d\n",
               GetOSVersionComponent(1),
               GetOSVersionComponent(2),
               GetOSVersionComponent(3)
               ) ;
    
        return 0 ;
    }
    

提交回复
热议问题