I'm trying to write a small C program that reads the Pi's serial number, just the serial number and not all the other information, to do this I'm using fseek here is my code, based on a few C examples and tutorials:

int main()


FILE *fp = fopen("/proc/cpuinfo", "r");

fseek(fp, -10, SEEK_END);

int ch = getc(fp);

while (ch != EOF)


/* display contents of file on screen */


    ch = getc(fp);


if (feof(fp))

   printf("\n End of file reached.");

   printf("\n Something went wrong.");


return 0;


I'm not getting any warnings or errors when compiling but it always seems to ignore the fseek and prints out the whole file. What am I doing wrong, or not doing right?

  • 2
    Check the returncode from fseek(). The entries in /proc aren't no real files. Use grep and cut to get the serial number.
    – ott--
    Jun 5, 2016 at 9:52
  • After the fseek use perror (include <errno.h>) to show the last error.
    – joan
    Jun 5, 2016 at 9:59
  • 1
    Ditto on (not) using streams to access proc/sys files -- while I have seen code where it is used, in my experience it's not reliable and so I always use low level open() and read() into a small buffer, then parse the buffer however you like. That method is totally reliable (I've use it to do ongoing multiple per second reads for extended time periods, which is how top and other system monitor tools work).
    – goldilocks
    Jun 5, 2016 at 11:38

1 Answer 1


You will have to do something along the following lines.

#include <stdio.h>
#include <stdint.h>

uint64_t getSerial(void)
   static uint64_t serial = 0;

   FILE *filp;
   char buf[512];
   char term;

   filp = fopen ("/proc/cpuinfo", "r");

   if (filp != NULL)
      while (fgets(buf, sizeof(buf), filp) != NULL)
         if (!strncasecmp("serial\t\t:", buf, 9))
            sscanf(buf+9, "%Lx", &serial);

   return serial;

int main(int argc, char *argv[])
   printf("%Lx\n", getSerial());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.