-1

My function gets a FILE* to read from, and it needs to read starting from some non-negative offset. I could use fseek(file, offset, SEEK_SET), but it fails on stdin, for instance.

How can I determine if fseek works? If it doesn't, I could read and discard offset bytes.

And is there a way to read (and discard) from FILE without allocating read buffer?

user2052436
  • 4,321
  • 1
  • 25
  • 46

2 Answers2

1

The return value of fseek() tells you if it worked or not:

Return Value
...Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, ...Otherwise, -1 is returned and errno is set to indicate the error.

So attempt to fseek() from the file and check the return result, and handle your failure case accordingly. Ex:

ret = fseek(stdin, 0, SEEK_SET);
if(ret < 0)
    printf("failed because: %s\n", strerror(errno));

will give you something like:

failed because: Illegal seek 

So that failed because you can't seek stdin, where as:

FILE * fp = fopen("word.txt", "r");
ret = fseek(fp, 0, SEEK_SET);
if(ret < 0)
    printf("failed because: %s\n", strerror(errno));

Wouldn't print anything because you got back 0 indicating success (assuming of course that "word.txt" exists, is readable, was opened successfully, etc).

I don't understand this part of your question:

is there a way to read (and discard) from FILE without allocating read buffer

You can just fseek() to the point you want to read, or you can read into an array to a buffer and then overwrite the results. The answer depends on your goals, but using things like fread() or read() will require a non-null pointer to store data into.

Mike
  • 47,263
  • 29
  • 113
  • 177
1

You can test if fseek works on that stream, by calling fseek( file, offset, SEEK_SET) and on error, checking that errno == EBADF which is returned to say "The stream specified is not a seekable stream".

I think you need to read and discard, with a buffer, but if it can just be pagesize bytes and you keep a count of bytes read, reading till you did the equivalent of a seek. If it were a memory mappable file, then you can read without reading, but then the seek would have worked.

Rob11311
  • 1,396
  • 8
  • 10