Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在内存中获取缓冲区的文件描述符?_C - Fatal编程技术网

C 如何在内存中获取缓冲区的文件描述符?

C 如何在内存中获取缓冲区的文件描述符?,c,C,如果我有一个包含文件数据的缓冲区,如何从中获取文件描述符? 这是一个来源于你不能回答的问题。与C++不同,文件I/O的C模型不允许扩展。p> 我写了一个简单的示例,说明如何将filedescriptor添加到内存区域: #include <unistd.h> #include <stdio.h> #include <string.h> char buff[]="qwer\nasdf\n"; int main(){ int p[2]; pipe(p); if(

如果我有一个包含文件数据的缓冲区,如何从中获取文件描述符?
这是一个来源于你不能回答的问题。与C++不同,文件I/O的C模型不允许扩展。p> 我写了一个简单的示例,说明如何将filedescriptor添加到内存区域:

#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("");
}
#包括
#包括
#包括
字符buff[]=“qwer\nasdf\n”;
int main(){
INTP[2];管道(p);
如果(!fork()){
对于(int buffsize=strlen(buff),len=0;buffsize>len;)
len+=写入(p[1],buff+len,buffsize len);
返回0;
}
关闭(p[1]);
文件*f=fdopen(p[0],“r”);
字符buff[100];
而(fgets(buff,100,f)){
printf(“来自子项:'%s'\n',buff);
}
认沽权(“”);
}

在普通C中不可能。在普通C中,所有文件访问都通过
文件*
句柄进行,这些句柄只能使用
fopen()
freopen()
创建,并且在这两种情况下都必须引用文件路径。由于C试图尽可能地具有可移植性,它将I/O限制在可能所有系统都能以某种方式支持的绝对最小值

如果您有可用的POSIX API(例如Linux、macOS、iOS、FreeBSD和大多数其他UNIX系统),则可以使用
fmemopen()


这是一个真正的文件句柄,可用于所有C文件API。它还应该允许查找,如果您使用管道,这是不可能的,因为管道支持不查找(您可以模拟向前查找,但无法向后查找)。

fmemopen可以从缓冲区返回FILE*,但fileno(fmemopen(…)返回-1。我还有一个想法:通过write()函数创建管道并将缓冲区内容馈送到文件_pipes[1],我们可以将文件_pipes[0]视为该缓冲区的文件描述符。但是当我练习这个时,write()函数就被阻塞了。管道的内核缓冲区不够大吗?谢谢这是POSIX,IIRC。不是C,这就是你如何标记你的问题。也就是说,它在Windows上不起作用。很好。作为适度的增强,您可以使用增加管道缓冲区大小。这要归功于。在Linux上,这可能很有用:它避免了使用for循环将数据写入管道。这是一个非常棒的解决方案,但如果您需要能够从fd(即seek)读取更多数据,那么这将不起作用。您不能在管道上搜索(至少不能在我使用的平台上搜索)。为什么不选择
fmemopen()
?是的,它是POSIX而不是C,但是
pipe()
也是POSIX,不是吗?@Mecki从手册页上看,
fileno()
在调用从
fmemopen()
返回的
文件时将返回
-1
char dataInMemory[] = "This is some data in memory";
FILE * fileDescriptor = fmemopen(dataInMemory, sizeof(dataInMemory), "r");