How to get file descriptor of buffer in memory?

后端 未结 3 609
野的像风
野的像风 2020-12-03 17:40

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

相关标签:
3条回答
  • 2020-12-03 17:46

    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("");
    }
    
    0 讨论(0)
  • 2020-12-03 17:58

    Not possible in plain C. In plain C all file access happens via FILE * handles and these can only be created with fopen() and freopen() and in both cases must refer to a file path. As C tries to be as portable as possible, it limits I/O to the absolute bare minimum that probably all systems can support in some way.

    If you have POSIX API available (e.g. Linux, macOS, iOS, FreeBSD, most other UNIX systems), you can use fmemopen():

    char dataInMemory[] = "This is some data in memory";
    FILE * fileDescriptor = fmemopen(dataInMemory, sizeof(dataInMemory), "r");
    

    This is a true file handle that can be used with all C file API. It should also allow seeking, something not possible if you work with pipes as pipes support no seeking (you can emulate forward seeking but there is no way to ever seek backwards).

    0 讨论(0)
  • 2020-12-03 18:13

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

    0 讨论(0)
提交回复
热议问题