How do you convert from a NSFileHandle to a FILE* structure?

27/07/03 18:54

I have a NSFileHandle but I want to use fprintf routine that need a FILE*. How to ?

NSFileHandle is a kind of wrapper of UNIX file descriptor: you can extract the file descriptor using

[myFileHandle fileDescriptor] method. Then the standard fdopen routine will give you a pointer on a FILE structure.That's the easy part. But now: which one do you need to close first: the FILE* by using fclose or the NSFileHandle using [myFileHandle closeFile] method ?The problem is as following: if you fclose(myFILE) first, then when releasing or closing the myFileHandle instance variable you will get an exception because the descriptor is already closed as a side effect. So lets close or release the myFileHandle before ? In that case, fclose will also return an error because of the now invalid file descriptor it is wrapping. Note that not calling fclose creates a memory leaks because the FILE structure internally allocated by fdopen is not released.One could think that closing the descriptor with [myFileHandle closeFile] and then free(myFile) is the solution. But we don't know if every implementations of fdopen allocate their FILE structures with malloc. Advice: avoid mixing NSFileHandle and FILE*…The solution is simply to use [[myFileHandle writeData:[[NSString stringWithFormat:…] dataUsingEncoding:myEncodingForThisJob]].stringWithFormat easily replace fprintf functionnality. For fscanf functionnality, look at NSScanner.