fgetpos/ftello without system call

Florian Weimer fweimer@redhat.com
Fri Sep 1 13:12:00 GMT 2017


On 09/01/2017 02:59 PM, Carlos O'Donell wrote:

> You should be able to do that, and it shouldn't trigger a seek.

It does not work as intended.

$ cat
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int
main (int argc, char **argv)
{
  if (argc != 3)
    errx (1, "usage: %s PATH BUFFER\n", argv[0]);
  FILE *fp = fopen64 (argv[1], "rce");
  if (fp == NULL)
    err (1, "fopen64");
  int length = atoi (argv[2]);
  if (length <= 1)
    errx (1, "invalid length");
  char *buffer = malloc (length);
  int lineno = 0;
  while (true)
    {
      off64_t offset = ftello64 (fp);
      if (offset < 0)
        err (1, "ftello64");
      fgets (buffer, length, fp);
      if (ferror (fp))
        err (1, "fgets");
      if (feof (fp))
        break;
      ++lineno;
      printf ("line %d at offset %lld: [[%s]]\n",
              lineno, (long long) offset, buffer);
    }
  if (fclose (fp) != 0)
    err (1, "fclose");
  free (buffer);
  return 0;
}
$ gcc -D_GNU_SOURCE -O2 -Wall -Werror=implicit-function-declaration
-Werror=implicit-int -o ftello-fgets -g ftello-fgets.c
$ strace -c -e lseek ./ftello-fgets /usr/share/misc/magic 500 > /dev/null
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.051526           2     25709           lseek
------ ----------- ----------- --------- --------- ----------------
100.00    0.051526                 25709           total
$ wc -l /usr/share/misc/magic
25708 /usr/share/misc/magic

Note sure what I'm doing wrong.

Thanks,
Florian



More information about the Libc-help mailing list