views:

1000

answers:

2

Hey,

Is there a platform-independent way of writing the EOF symbol to a string in Ruby. In *nix I believe the symbol is ^D, but in Windows is ^Z, that's why I ask.

Cheers

Pete

+5  A: 

EOF is not a character, it's a state. Terminals use control characters to represent this state (C-d). There's no such thing is "reading a EOF character" and same thing for writing one. If you're writing to a file, just close it when you're done. See this mailing list post:

It sounds like you are thinking of EOF as an in-band but special character value that marks the end of file. It is better to think of it as an out-of-band sentinel value. In C, EOF is usually -1 and the associated API specifies integer return values so that EOF is guaranteed to never be confused with a valid in-band value.

Here's some more proof (do this on Unix):

$ cat > file
hello^V^Dworld
^D
$ cat file
helloworld

Typing ^V^D inserts a control-D character literally into the file. After typing world and enter, the ^D closes the pipe. The file ends up being 12 bytes long 10 letters, two more for the ^D and the newline. The final ^D does not end up in the file. It's just used by the terminal/shell to close the pipe.

Mark A. Nicolosi
it's a very common misconception that EOF is a character
GogaRieger
+1  A: 

In general there is no EOF character. That is, there's no cross-platform solution to this and even on specific platforms the handling of such a character is purely legacy and inconsistent. You end a file by closing it.

However, to be pedantic, certain operating systems when reading files in certain modes do support a literal end of file character. For example, if you're running under Windows and use the C stdio API to read a file in text mode then a literal control-Z (character code 26) will signal end of file to stdio. This is a holdover from MS-DOS which it has as a holdover from CP/M. If you use stdio and read the file in binary mode then the control-Z will not end the file.

Nevertheless, you should only think of it as "know, don't use" feature. You'll want to know about it if you ever see trucated input/output on Windows, but using it is madness.

George Phillips