[英]How to read from pipe into a file?
我想从 pipe 直接读取到具有以下代码的文件中。 base_fd 是 pipe。
FILE* fp = fopen("dec_data", "wb+");
int r_result;
int len = msg_length-part-3; //set to 75933
while ((r_result = read(base_fd[0], fp, len))) {
printf("r_result: %d \n", r_result);
len -= r_result;
}
读取似乎很好,r_result 显示 65536,然后根据需要显示 10397。 但是,当我检查我创建的文件时,它的大小为 0 字节......
您的代码中有语义错误。 看一下read(2)系统调用签名:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
function 的第二个参数是一个void
指针 ( void *buf
), read
将存储从fd
描述符读取的count
字节。
但是, FILE *
是C library
的抽象。 在这个答案中,您可以看到更多。 MinGW32 5.1.4 中的struct FILE
是:
typedef struct _iobuf
{
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;
read 的作用类似于我们复制字符串的方式。 考虑这个 function:
void strcpy(char *dst, char *src)
{
while(*src) *dst++ = *src++;
}
这个 function 会将内容从src
复制到dst
,直到找到NULL
终止字节。 这显然是一个非常有缺陷的 function 并且永远不应该使用,但说明了为什么您的示例不起作用。
在幕后, read
所做的与这个strcpy
function 非常相似:它从fp
指针指向的地址开始覆盖 memory 中的很多字节。 您实际上失去了对FILE *
指针和与之关联的资源的引用。
我敢打赌,如果您在该循环之后尝试close(fp)
,您会遇到分段错误(这是未定义的行为,但我还是打赌)。
做你想做的事情的正确方法是:
FILE* fp = fopen("dec_data", "wb+");
char *buf;
int r_result;
int len = msg_length - part - 3; //set to 75933
buf = malloc(len);
if(!buf) {
perror("malloc");
exit(EXIT_FAILURE);
}
while ((r_result = read(base_fd[0], buf, len))) {
fprintf(fp, buf);
len -= r_result;
}
free(buf);
close(fp); // now it closes the file pointer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.