简体   繁体   中英

How to read procfs file?

I tried to read the /proc/modules using standard c functions:

FILE *pfile;
int sz;
pfile = fopen( "/proc/modules", "r" );
fseek( pfile, 0, SEEK_END );
sz = ftell( pfile );
rewind( ftell );

But my problem is ftell give me 0 value. So I can't read the contents of the file since I have a zero length. Is there another way that I can get the size of the file that I want to read?

Many thanks.

No, it does not have a size. However, you can read parts of it until you reach end-of-file.

/proc files are dynamically created when you read them, so they cannot have a size.

I stand corrected. Some /proc files do indeed have a size, as adobriyan has noted on a comment to Sjoerd's answer. (Is that Alexey Dobriyan of Linux Kernel fame?)

As for how to read the file using fgetc, this works:

int c;
while ( (c = fgetc(pfile)) != EOF) {
    printf("%c",c);
}

And your program is segfaulting because you're trying to rewind ftell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM