ahota
ahota

Reputation: 449

Why is the beginning of a C file stream called `SEEK_SET`?

There are three origin constants you can use in functions like fseek to determine from where your offset is counted: SEEK_SET, SEEK_CUR, and SEEK_END. SEEK_CUR and SEEK_END seem self-explanatory to mean the current position and end of the file stream, but why is SEEK_SET used to mean the beginning? Why not something like SEEK_BEG?

Upvotes: 6

Views: 10459

Answers (2)

Steve Summit
Steve Summit

Reputation: 47933

Another answer to the question as stated is "Because fseek has a second argument which isn't always zero".

If you always passed the second argument as zero, then SEEK_CUR would set the file pointer to its current position (which would be a nearly useless no-op), and SEEK_END would set the file pointer to the end of file, and SEEK_SET would set it to the beginning of the file, which might make you wonder why it wasn't called SEEK_BEG.

But of course fseek does have that second argument, and you usually pass it as an interesting, non-zero offset. Much of the time, the second argument is the absolute offset you want to seek to, which is what SEEK_SET means. As a convenience, you can also set a position plus-or-minus the current position, which is what SEEK_CUR is for, or plus-or-minus the end of the file, which is what SEEK_END is for.

In the case that whence is SEEK_SET and the offset is 0, meaning that you're trying to set the file pointer to the beginning of the file, there maybe ought to be a convenient shortcut for that, too. But the shortcut isn't called SEEK_BEG, it's a completely different library function: rewind(fp), which is indeed a shortcut for fseek(fp, 0L, SEEK_SET).

Upvotes: 1

stena
stena

Reputation: 785

Because you can add an offset. By using SEEK_SET, you can explicitly set an offset. (By adding it to the beginning)

From the manpage of fseek:

The new position, measured in bytes, is
obtained by adding offset bytes to the position specified by whence.
If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is
relative to the start of the file, the current position indicator, or
end-of-file, respectively.

From the manpage of lseek:

   SEEK_SET
          The file offset is set to offset bytes.

   SEEK_CUR
          The file offset is set to its current location plus offset
          bytes.

   SEEK_END
          The file offset is set to the size of the file plus offset
          bytes.

Upvotes: 12

Related Questions