1

I want to read last n bytes of proc file /proc//status.

On regular files, I can fseek from the end of the file like:

fseek(proc_file, -BUF_SIZE, SEEK_END);

but since the proc file has zero size, this doesn't work.

Any suggestions on how to read from the end ?

I would definite want to avoid looping till the end.

L Lawliet
  • 2,565
  • 4
  • 26
  • 35

1 Answers1

1

The status file is small. Just fread the first 10000 bytes:

int fileLen = fread( statusFile, buffer, 10000 );

fread will return the number of bytes in the file along with the contents of the file. You can then check the end of the file.

There is no advantage to reading just the last few bytes. File i/o systems are buffered, such that asking even for a few bytes will cause the lower layers to read a couple of k anyway.

Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
  • I'd bet 1024 bytes should be enough. I did `for file in $(ls -1 /proc | egrep '^[0-9]+$'); do wc -c /proc/$file/status 2> /dev/null; done | sort -n` on my system and the minimum was 532, while the maximum was 850. Maybe err on the conservative side and do 4096. – mpontillo Sep 27 '14 at 02:56
  • 2
    WRT buffering: This is true for normal file systems, but *not* true for procfs. It's not backed by a block device, so there's no caching. Read operations are fulfilled directly by the kernel. –  Sep 27 '14 at 04:32
  • @Mike I have seen it go over 1k specially on clusters but yes I also end up using 4k. – L Lawliet Sep 28 '14 at 07:57
  • @duskwuff: yes and no. I understand that procfs isn't a block device and doesn't do the that kind of cacheing. But I think for these fake kernel space files in /proc, that the "files" don't actually exist - but are rather kernel space binary data structures - non text. On open or maybe read, the structures are serialized to a buffer. Reading just part of it will still cause the whole buffer in kernel space to be generated. – Rafael Baptista Sep 28 '14 at 18:29