2

I am re-reading the /proc/stat file to get the updated values. First I opened the file, read each line, closed the file and re-opened to get the updated values. I want to know if closing a file is necessary or I can achieve the same effect by seeking to starting of the file. I wrote a code which did not close the file, instead placed the file pointer to the beginning of the file, which worked as before. But I wanted to know that will seeking to the starting of the file gurantee that I will get the updated information?

Edit: Another point, I am sleeping between the seeks and reads.

Although this question is not language specific here are the implementation languages in context: C, Perl.

EDIT

Here is the code I wrote.

while ()
{
  open (STAT, "/proc/stat") or die "Cannot open /proc/stat\n";
  while (<STAT>)
  {
    #Stuff here
  }
  close (STAT);
  sleep 1;
}

Vs.

open (STAT, "/proc/stat") or die "Cannot open /proc/stat\n";
while ()
{
  seek STAT, SEEK_SET, 0;
  while (<STAT>)
  {
    #Stuff here
  }
  sleep 1;
}
close (STAT);

Which one is preferable?

phoxis
  • 60,131
  • 14
  • 81
  • 117
  • possible duplicate of [Is it safe to use lseek() when reading from Proc-FS files second time](http://stackoverflow.com/questions/4788462/is-it-safe-to-use-lseek-when-reading-from-proc-fs-files-second-time) – falsetru Aug 08 '13 at 12:55

1 Answers1

0

Both of those should work. seek should clear the EOF flag on your filehandle so you can read it a second time, but if you need to be absolutely sure you're getting a fresh copy, I would go with closing and re-opening.

See seek for more information.

Mintx
  • 151
  • 4