tags:

views:

355

answers:

2

If I have a buffer which contains the data of a file, how can I get a file descriptor from it? This is a question derived from how to untar file in memory

A: 

You can't. Unlike C++, the C model of file I/O isn't open to extension.

MSalters
fmemopen can return FILE* from buffer, but fileno(fmemopen(...)) return -1. I got another idea: create pipe and feed buffer content to file_pipes[1] by write() function, and we can look the file_pipes[0] as the file descriptor of that buffer. But when I practise this, the write() function just blocked. Is the kernel buffer of pipe not big enough? Thanks
solotim
That's POSIX, IIRC. Not C, which is how you tagged your question. I.e. it wouldn't work on Windows.
MSalters
+2  A: 

I wrote a simple example how to make filedescriptor to a memory area:

#include <unistd.h>
#include <stdio.h> 
#include <string.h> 

char buff[]="qwer\nasdf\n";

int main(){
  int p[2]; pipe(p);

  if( !fork() ){
    for( int buffsize=strlen(buff), len=0; buffsize>len; )
      len+=write( p[1], buff+len, buffsize-len );
    return 0;
  }

  close(p[1]);
  FILE *f = fdopen( p[0], "r" );
  char buff[100];
  while( fgets(buff,100,f) ){
    printf("from child: '%s'\n", buff );
  }
  puts("");
}
sambowry