5

i have been scratching my head and been searching for an answer for this for hours now. Basically what I do is open a socket to some other machine and reading the data from it. This socket is than "converted" to a file handle via an fdopen call passing in the int that represent the socket. The resulting file handle is then passed to a bison parser which directly parsed the data received over the socket. All of this works fine on linux. Now I have tried to port this code to windows and I dismally fail. The code looks something like this:

        FILE* fileHandle;
        #if defined WINCE || defined WIN32
        int fd = _open_osfhandle(socket, _O_RDONLY);
        if (fileHandle = fdopen(fd, "r")) {
        #else
        if (fileHandle = fdopen(socket, "r")) {
        #endif
           ... // code to call my parser with fileHandle as argument

The bison/flex parser fails in the windows version since the filehandle seems to point to an empty stream/file. Can anybody point to a comprehensive resource that explains this stuff or hint at an alternative solution?

Thanks and best Regards,

André

André
  • 61
  • 1
  • 4

2 Answers2

9

In Windows, a socket handle is not a file handle, and you cannot treat it as such in the C API. In Linux, you can. However, in Windows, a socket handle can be passed to the ReadFile/Ex() and WriteFile/Ex() functions, which support numerous handle types, not just files, despite their names.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • This does not help me directly since the code that I call is basically generated. I cannot call the windows specific functions inside it unless I create some wrapper or override some of the flex/bison generated code which I would like to avoid. – André Apr 09 '12 at 20:00
  • 1
    Then you are out of luck. You need to re-write something. You can't use C file I/O functions on a socket handle in Windows. – Remy Lebeau Apr 09 '12 at 21:26
  • Yeap that is also my conclusion. Parts of this need to be rewritten. – André Apr 14 '12 at 10:37
-1

You need to fake a little bit, but this one works for me - nSocketFd a file descriptor return by socket()

    FILE* fpSocket = NULL;

#ifdef WIN32
    fpSocket = new FILE;
    fpSocket->_file = nSocketFd;
    fpSocket->_cnt = 0;
    fpSocket->_ptr = NULL;
    fpSocket->_base = NULL;
    fpSocket->_flag = 0;
#else
    // build the file pointer from the file descriptor
    fpSocket = fdopen (nSocketFd, "rb+");
#endif