8

I got a descriptor for a TCP socket in the following manner :

int desc = accept(socket_descriptor, &client_address, &len)

Now from this descriptor desc I want to get a file pointer. Can fdopen() be used here ?

The reason I want to get a file pointer is because I am making changes to an existing code that writes data to a local file. Now, I want to extend its functionality so that it can alternatively write to a TCP client. I dont want to rewrite all functions and was thinking of somehow being able to use the existing infrastructure. The existing functions use the file pointer to write to the file. I was wondering if it was possible to make the same function write to a TCP stream without making any changes.

Matthew Slattery
  • 45,290
  • 8
  • 103
  • 119
AnkurVj
  • 7,958
  • 10
  • 43
  • 55

1 Answers1

10

Yes, fdopen() is exactly what you need. Here is what man page is saying about it:

The fdopen() function associates a stream with the existing file descriptor, fd. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fd, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed. The result of applying fdopen() to a shared memory object is undefined.

But use it with caution when applying to socket descriptors. High-level I/O functions use buffering, and may send data differently (i.e. flush whenever \n is found in the stream, insert \r) etc.

  • 1
    Most files aren't line buffered, only `stdout`. I'm not sure if there's a way to set a file to be line buffered, but I believe most will be block buffered, which should be a bit more socket friendly. – Chris Lutz Oct 15 '11 at 22:26
  • @ChrisLutz: The function is `setlinebuf`. I think `stdout` is only line buffered if it's hooked to a terminal, but I'm not sure. – Dietrich Epp Oct 15 '11 at 22:33
  • @DietrichEpp - Thank you. And I think you're right about `stdout`. – Chris Lutz Oct 15 '11 at 22:37
  • I am concerned about the line that says " The mode of the stream must be compatible with the mode of the file descriptor". Should I use "w" in my scenario? – AnkurVj Oct 15 '11 at 22:37
  • 2
    @AnkurVj: Why don't you try it out? I'd recommend starting with "w+" or "bw+" if text and binary files are treated differently (i.e. on Windows). –  Oct 15 '11 at 22:47
  • I've tried "a+" and "r+". "r+" works only in Mac OS X/iOS, whereas "a+" also works for Linux 3.2.0. – ZhangChn Feb 05 '13 at 18:18
  • @ZhangChn: r+ Works for me on Linux. –  Feb 08 '13 at 22:25