1

I'm trying to store the number of page faults into an array in my c program. I want to execute bash command and store the output of it in an array. here's my command

$ cat /proc/vmstat | grep pgfault
2
  • popen() plus fread(). Commented Sep 10, 2014 at 20:49
  • Include that line in your C program that creates an array and then prepares to store the data within a loop. Commented Sep 10, 2014 at 22:36

1 Answer 1

1

A simple start, can be embellished and improved...

char * lines[2000];         /* 2000 lines enough? */
int    n = 0;

FILE * fp = popen("your command here", "r");
if (fp == NULL) abort();

lines[0] = malloc(1000);    /* 1000 byte lines enough? */
while ((fgets(lines[n], 1000, fp) != NULL) {
    if (n == 1999) abort();       /* oh crud... */
    lines[++n] = malloc(1000);
}
free(lines[n]);
pclose(fp);
/* do something with lines[0 .. n-1] here */
/* then free them */
Sign up to request clarification or add additional context in comments.

1 Comment

It sure can be embellished, perhaps by avoiding leaking 1999 lines (in the worst case).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.