lelephantt
lelephantt

Reputation: 169

How to get product name/version in C/C++ for macOS (ie get "Mac OS" and "10.12.5")

I need to get the information in the title. I made sysctl calls to the following variables and it gave me other (not useful) information (usually regarding the kernel not the OS): KERN_VERSION, KERN_OSVERSION, KERN_TYPE, KERN_RELEASE.

I looked at the source code for the command sw_vers here: https://opensource.apple.com/source/DarwinTools/DarwinTools-1/sw_vers.c and tried to implement what they did however while I was able to include my computer was unable to find and thus I coulnd't implement. When I look through my /include/ directory I can't find /CoreFoundation/ at all so I don't know where I'm pulling it from.

Any ideas on how I can get this using C/C++?

Thanks

Upvotes: 4

Views: 2604

Answers (1)

jxh
jxh

Reputation: 70472

If this were my project, I would simply invoke the sw_vers utility and parse its output. You can use popen to accomplish this, illustrated below:

char buf[1024];
unsigned buflen = 0;
char line[256];
FILE *sw_vers = popen("sw_vers", "r");
while (fgets(line, sizeof(line), sw_vers) != NULL) {
    int l = snprintf(buf + buflen, sizeof(buf) - buflen, "%s", line);
    buflen += l;
    assert(buflen < sizeof(buf));
}
pclose(sw_vers);

Parse the output to get the relevant information. On my system, the output is:

ProductName:    Mac OS X
ProductVersion: 10.12.5
BuildVersion:   16F73

So, you could parse each line instead of storing it all into a buffer as illustrated.

Once the information is stored in your program, the result can be cached. Any future queries by your same program can use the cached result rather than invoking sw_vers again.

Upvotes: 5

Related Questions