Pages

Tuesday, July 3, 2012

Converting a file descriptor to an I/O Stream in Linux [C++]

Recently, if one can call something that happened over 2 months ago 'recent', I decided to do a Networks assignment entirely in C++ and using streams. Why, you ask ? Well, the simplest answer is, "I was bored." I had done another network assignment in C, through which I had seen quite a lot of functions that are required to connect, send/receive messages, etc. So, this was something like a challenge.

And that's exactly what it turned out to be, a challenge. Four hours into the assignment, which was obviously just 2 days before the submission, I was struggling to understand how could I convert all the file descriptors that were being returned from various C based functions into C++ streams.

As it turns out, due to difference in uses and implications of file descriptors in different operating systems, there was no standard function to convert a File Descriptor to a stream.  That was what I learnt after hours of scouring over StackOverflow and running into answers that explained "How to get the underlying FILE* from fstream?" until I finally found out a solution that works on G++.


This may definitely not be the best approach, but a hack.

I used it here and built upon it. Besides the problem of handling Unicode characters (which I understand was because I was using string and not wstring ), I did not face any problem with streams; so I would assume that the solution worked well.

If you are aware of a smarter, quicker and cleaner method of doing this, please share it in comments.