Reputation: 13
I am kinda new to C (haven't used it a long time) and I have a little problem with my code. I try to read a file, count the lines, and store the numbers in 2D array of integers. After counting lines in the file, I have to open the file again because, after the do while
cycle I can't read anything from the file. Is there any option how to avoid opening the file again to store values?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int disk[10][10];
int i, j, num, row=0, col=4;
int ch;
FILE *diskfile1;
diskfile1 = popen("grep 'sda' /proc/diskstats | awk '{print $4,$6,$8,$10}'", "r");
do {
ch=fgetc(diskfile1);
if(ch=='\n')
row++;
}while(ch != EOF);
FILE *diskfile;
diskfile = popen("grep 'sda' /proc/diskstats | awk '{print $4,$6,$8,$10}'", "r");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
fscanf(diskfile, "%d ", &num);
disk[i][j] = num;
}
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", disk[i][j]);
if(j==col-1)
printf("\n");
}
}
}
Upvotes: 0
Views: 41
Reputation: 7161
You have discovered one limitation of reading a piped process (popen()
) instead of a file (fopen()
). It is just a stream of data, not a file where the entire contents are known and persistent. For a stream, the only thing you know is what's next and if you're at the end or not. If it were a true file, you could seek around wherever you want, forwards or backwards. With a stream, you can only read forwards.
So if you want to read to the end, then read the contents again, you would have to do it in two passes (like your example). But the second time you run the command, it may or may not give the exact same result.
I would suggest to read the data and store it using only one pass. You could read data and store it row by row, and dynamically reallocate your buffer as needed.
Upvotes: 2