3

I try to understand the seek(2) function from Unix version 6.

This example:

seek(0,0,2)

So the first argument is the file descriptor. And 0 would be the standard input. The second argument is the offset, which is 0. And the third argument tells us according to man page "the pointer is set to the size of the file plus offset."

But why would you do this? Why would you point after the file?

The line is from the source code.

4

The seek(0, 0, 2) will skip over all data that is buffered up for file descriptor 0. So after this command, the next read from that filedescriptor will not read anything that was buffered.

I think if you examine the code and understand what the actual purpose is, you'll understand that even though file descriptor 0 is normally stdin, this program is really only useful if it is part of a script that is read through that file descriptor.

For example, take a look at the following script:

goto
echo "hello"

The goto without any argument is going to trigger the seek.

Without the seek(0, 0, 2) after the goto command exits, the script would still run the echo "hello" command because the caller of the goto command is simply going to read the next command from the script.

1

You would want to rewind the standard input before returning because of an error condition.

if (argc<2 || ttyn(0)!='x') {
    write(1, "goto error\n", 11);
    seek(0, 0, 2);
    return;
}
  • 1
    But why would you rewind the standard input? What would happen if you don't? – Joey Dec 28 '14 at 15:03
1

seek and fseek are used to change the current position in a file (file descriptor (seek) or file pointer (fseek)). In C, I normally use fseek. Some typical uses of seek/fseek from the end of file (SEEK_END):

Position in the end of the file = seek(f,0,2) or fseek(f,0,2)

Calculating the size of a file = fseek(f,0,2); size=ftell(f)

Position in end of file minus 20 = fseek(f,-20,2)

Some "files" can not be re-winded

1

It's not after the file since the offset is 0, so it points to the end of the file, usually used for appending data to a file.

This is done with stdin to go past the input that has been written and not read, it is inaccurate to refer to it as a buffer since if the stdin is a pipe, it is read until no further reads are possible.
The passwd command does this to prevent cases where there's input that is not part of the password itself (such as duplicate presses on return) and to prevent basic scripting of the interaction with it.

  • but what is the file in this context? 0 would be the standardinput. So you would point to the end of the standardinput? Why? – Joey Dec 28 '14 at 15:01
  • very good question @user3704943 answered it :-) – f01 Dec 28 '14 at 19:24
  • Edited to add a response to that. – Didi Kohen Dec 30 '14 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.