in reply to Re: CGI File upload, resulting files 0 bytes long
in thread CGI File upload, resulting files 0 bytes long

Lincoln Stein describes binmode() in his most meritorious work Network Programming With Perl. He writes:
In text mode, however, the standard I/O library automatically translates LF into CRLF pairs on the way out, and CRLF pairs into LF on the way in. The virtue of this is that it makes text operations on Windows and UNIX Perls look the same—from the programmer's point of view, the DOS text files end in a single \n character, just as they do in UNIX. The problem one runs into is when reading and writing binary files—such as images or indexed databases—and the files become mysteriously corrupted on input or output. This is due to the default line-end translation. Should this happen to you, you should turn off character translation by calling binmode() on the filehandle.
Generally one ought not to run binmode() when one is reading and writing text on Windows and VMS system. But reading between the lines of Stein's advice makes me think that perhaps one ought to turn on binmode only as needed even when running binary files.

When I used to open up DOS binary files in text editors I would often see what looked like meaningful text there. Perhaps "to every thing there is a season" as it says in Ecclesiastes and even binary files should sometimes be run without binmode() in order to handle these meaningful snippets of text in binary files.

  • Comment on Re: Re: CGI File upload, resulting files 0 bytes long

Replies are listed 'Best First'.
(tye)Re: CGI File upload, resulting files 0 bytes long
by tye (Sage) on Mar 07, 2001 at 04:20 UTC

    Yes, I get the same "between the lines" impression, but that doesn't change the fact that such advice is just wrong.

    Always use binmode() when dealing with binary data in files and never use bindmode() when dealing with only text data in files.

    If you read a binary file without binmode() in DOS and expect to find the text bits in better shape, then you will be surprised when the binary data contains CTRL-Z and your program refuses to read past that, no matter how much text appears later in the file.

    I find particularly unfortunate the "Should this happen to you" bit. "Well, I know it is possible that dealing with binary files w/o binmode() might cause problems but you should really wait to fix such problems until such time as you stumble upon them."

    I'm disappointed at how frequently discussions of binmode() say stuff like "Use this if you aren't on Unix and...".

            - tye (but my friends call me "Tye")
      Actually, I wondered about the "should this happen to you" also. What if it happens after the code is in production, and "you" are on your next assignment?

      I know that Lincoln Stein is a genius, but it seems as if on this he is wrong.