How do I get the current battery level?

What I'd like to do is just develop a little program that outputs the battery level as a percentage, but I can't find a way to do this without invoking the shell. I want to only use system libraries.

Please help and thank you!
> without invoking the shell.
If you know a program that does it, then look at its source code to learn how to do it.


By instance, acpi traverse the /sys/class/power_supply/ directory and for each device it parses the files.
OK, I've decided to revert to using the shell. My operating system (Mac) has a program I'd like to use called System Profiler. I'm having a little problem, though. I get an errno of 29 after fell.

Here's the source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string systemProfilerOutput()
{
    FILE *profilerPipe = popen("system_profiler -detailLevel basic", "r");
    fseek(profilerPipe, 0, SEEK_END);
    long length = ftell(profilerPipe);
    checkErrno();
    fseek(profilerPipe, 0, SEEK_SET);
    char *buffer = 0;
    fread(buffer, 1, length, profilerPipe);
    pclose(profilerPipe);
    checkErrno();
    string profilerOutput;
    profilerOutput = string(buffer);
    return profilerOutput;
}
Last edited on
OK, error 29 means "illegal seek", meaning seek operations on pipes aren't valid.

Instead, what I need to do is create a char[] array that acts as a buffer, a temporary holding place for each line of output. This buffer can then be appended to a C++ string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string systemProfilerOutput()
{
    FILE *profilerPipe = popen("system_profiler -detailLevel basic", "r");
    // Read the output.
    string profilerOutput;
    char buffer[256];
    while (!feof(profilerPipe)) {
        if (errno && errno != 4) {
            throw errno;
        }
        if (fgets(buffer, 256, profilerPipe)) {
            profilerOutput.append(buffer);
        }
    }
    pclose(profilerPipe);
    return profilerOutput;
}
Topic archived. No new replies allowed.