Search code examples
clinuxfilefilestream

How to read file size of /proc/cmdline


I have

FILE *file = fopen("/proc/cmdline", "r");
struct stat st;
fstat(file, &st);
char buffer[st.st_size];
fgets(buffer, st.st_size,file);
printf("%s", buffer);

By luck this prints out the contents of cmdline but I have an int pointer conversion warning at the fstat() function. If I try fstat(fileno(file), &st); the buffer has gibberish meaning st.st_size wasn't properly set. Like wise seeking to the end of file to get it's size also is not setting the size of the buffer properly

It seems st.st_size contains a number with a leading zero eg 01315 hence gibberish out put


Solution

  • How to read file size of /proc/cmdline

    (Assuming Linux) like so (error checking omitted for brevity):

    #include <limits.h>
    ...
    
    char buf[ARG_MAX];
    FILE *fp = fopen("/proc/cmdline", "rb");
    size_t len = fread(buf, sizeof(buf), 1, fp);