I am running Ubuntu and I don't understand why it's so hard for me to get the number of cores on my system in C! I've tried parsing /proc/cpuinfo
with success on my system running Ubuntu but then I tried on another system running arch linux which would fail because the buffer was too small, and I can't seem to figure out how to make it work on both of my systems.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
char *buffer, *tmp;
size_t bytes_read, size;
if((fp = fopen("/proc/cpuinfo", "r")) == NULL) {
perror("open failed");
exit(EXIT_FAILURE);
}
size = 1024;
if((buffer = malloc(size)) == NULL) {
perror("malloc failed");
free(buffer);
exit(EXIT_FAILURE);
}
while(!feof(fp)) {
bytes_read = fread(buffer, 1, size, fp);
if(bytes_read == size) {
size += 128;
if((tmp = realloc(buffer, size)) == NULL) {
perror("realloc failed");
free(buffer);
exit(EXIT_FAILURE);
}else {
buffer = tmp;
}
}
}
fclose(fp);
if(bytes_read == 0 || bytes_read == size) {
perror("read failed or buffer isn't big enough.");
exit(EXIT_FAILURE);
}
printf("%d bytes read out of %d\n", (int)bytes_read,(int) size);
buffer[bytes_read] = '\0';
printf("%s", buffer);
}
This outputs 572 bytes read out of 1152
, but it overwrites the buffer whenever I use fread
again. And I can't use sysconf(_SC_NPROCESSORS_ONLN);
either because it doesn't work on Ubuntu it seems.