You are not logged in.

#1 2010-04-27 00:28:30

Basu
Member
From: Cornell University
Registered: 2006-12-15
Posts: 296
Website

Opening /proc files from a C program

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

#2 2010-04-27 02:43:28

Kiwi
Member
Registered: 2008-02-24
Posts: 153

Re: Opening /proc files from a C program

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

#3 2010-04-27 03:43:13

tavianator
Member
From: Waterloo, ON, Canada
Registered: 2007-08-21
Posts: 859
Website

Re: Opening /proc files from a C program

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

#4 2010-04-27 16:19:32

Basu
Member
From: Cornell University
Registered: 2006-12-15
Posts: 296
Website

Re: Opening /proc files from a C program

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

Board footer

Powered by FluxBB