You are not logged in.
Hey all,
I'm trying to write a C program that gets some info from the /proc filesystem (stuff like uptime and version) and I'm using a plain C fopen() on the files in /proc. But all I get is a file of size 0. I know that /proc isn't a real filesystem, but I was hoping I could use standard C file operations to read them. The permissions seem to be set right (I can see them with cat). Is there some special way to get to them from a C program?
Thanks
The Bytebaker -- Computer science is not a science and it's not about computers
Check out my open source software at Github
Offline
Through google I have found this. "./a.out cpuinfo" worked for me
#include <stdio.h>
#include <stdlib.h>
#define BS 1024
void die(char *x){ perror(x); exit(1); };
int main(int argc, char **argv)
{
int n = 0;
char filepath[BS], buf[BS];
FILE *f = NULL;
//get the filename to open
if(argc < 2){
fprintf(stderr, "Usage: %s <proc file>\n", argv[0]);
return 1;
}
//get the path of the file
n = snprintf(filepath, BS-1, "/proc/%s", argv[1]);
filepath[n] = 0;
//open the file
f = fopen(filepath, "r");
if(!f)
die("fopen");
//print its contents
while(fgets(buf, BS-1, f))
printf("%s", buf);
if(ferror(f))
die("fgets");
fclose(f);
return 0;
}
Offline
As ls -l /proc/cpuinfo will show you, most files in /proc are treated as if they are 0 bytes long. Reading still works though.
Offline
Thanks, I have to have the whole /proc file in memory for my needs, but I managed to do it using fgets() and populating buffers instead of printing.
The Bytebaker -- Computer science is not a science and it's not about computers
Check out my open source software at Github
Offline