RudeServerProfessional C++ CGI Development Libraries
CGI Parser Logo

  RudeCGI file upload tutorial part 3


RudeServer Home
API Documentation
Basic Usage

   File Upload Tutorial
Visual C++ CGI Tutorial

Discussion Forum
Revision History


File Upload Tutorial - part 3

<- Prev | Next ->

Windows vs. Linux Gotchas

There are some gotchas and headaches that come with working with uploading and downloading files through CGI. The problem is based on when and how to set a file stream to binary mode and when to set it (or keep it) in text mode.

If you send a binary file (one that might contain NULL characters and newlines/CRLF's that aren't meant to be CRLF's) to a file stream in text mode oni a windows machine, CRLF's are going to get converted to the local CRLF sequence, which corrupts the file. Likewise, if you download a text file in binary mode, there are times when the browser will add, keep, or delete newline characters. In these cases, the text file might have a mysterious blank line between every line in the file, or the newlines might get erased, and you just have one long line. Anyway, you get the idea. The problem is exacerbated when you have a script working on one platform and try to port it to another - linux vs. windows.

I recently installed the latest version of Red Hat Linux, and use it as my main computer. I was writing an upload script, and was trying in vain to figure out how to convert stdin and stdout to binary mode. To make a long story short, all linux files are in binary mode by default. The "b" flag used to set binary mode in fopen(), fdopen(), and freopen() is ignored in linux. If I would have read the man pages closer I would have discovered that all POSIX compliant OS's treat text and binary files the same, so there is no need to worry about text vs binary mode on my machine. Windows is a different story.

In windows, if a file uploaded is content type "text/.....", then you want to use Ascii mode whenever you deal with the file. Otherwise, you want to use Binary mode whenever you deal with the file. By dealing with the file, I mean - sending it to stdout, reading it from stdin, writing it to a file, reading it from a file, etc....

Anyway, here's the code you need in windows to set stdin or stdout to binary mode:

  1. First - you need to include this header in Windows:

    #include <io.h>

  2. Then, when you want to set stdout (or stdin) to binary mode, use this code:

    int result = setmode( fileno( stdout ), O_BINARY );
    if(result != -1)
    // yay! - successfully set it binary mode
    // I hate windows


<- Prev | Next ->


Copyright ©2000 RudeServer