I have third-party C code that writes data to a file. I want to modify that code so it writes the exact same data to a datagram socket instead.
A pointer to FILE is handled over to the third-party code to determine which file to use. The data is written to the file exclusively using fwrite().
Everything would be fine if the code would use write() instead of fwrite() because write() works on both sockets and files. It expects an integer as file descriptor which is the data type both socket() and open() return.
However, since the third-party code uses fwrite(), this task is not that easy. I wonder what would be the best way to get this task done.
Should I write a fwrite() function that does the same job as the original fwrite() using write() internally? Or is there a hack to “cast” an integer file descriptor to FILE*?
You can turn a socket into a
FILE *by usingfdopen:I hope you are using a sequential datagram protocol (i.e., Unix datagram socket, not UDP socket), because otherwise, your data is going to get messed up.
If you are using UDP: The packets can be arbitrarily dropped or re-ordered, and since the code using the
FILE *assumes that it’s writing to disk, you’ll get a big mess when you try to put everything together on the other side.