[英]How to read from pipe into a file?
I would like to read from the pipe straight into a file with the code below.我想从 pipe 直接读取到具有以下代码的文件中。 base_fd is a 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;
}
The read seems to happen fine, with r_result showing 65536 and then 10397 as required.读取似乎很好,r_result 显示 65536,然后根据需要显示 10397。 However, when I inspect the file I created, it has a size of 0 bytes...
但是,当我检查我创建的文件时,它的大小为 0 字节......
You have a semantic error in your code.您的代码中有语义错误。 Take a look at the read(2) system call signature:
看一下read(2)系统调用签名:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
The second parameter to the function is a void
pointer ( void *buf
), which is where read
will store the count
bytes it reads from fd
descriptor. function 的第二个参数是一个
void
指针 ( void *buf
), read
将存储从fd
描述符读取的count
字节。
However, a FILE *
is an abstraction of the C library
.但是,
FILE *
是C library
的抽象。 In this answer you can see more of it.在这个答案中,您可以看到更多。 The
struct FILE
in MinGW32 5.1.4 is: 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;
What read will do is similar to how we copy strings. read 的作用类似于我们复制字符串的方式。 Consider this function:
考虑这个 function:
void strcpy(char *dst, char *src)
{
while(*src) *dst++ = *src++;
}
This function will copy the contents from src
into dst
until it finds a NULL
terminating byte.这个 function 会将内容从
src
复制到dst
,直到找到NULL
终止字节。 This is obviously a very flawed function and should never be used, but illustrates why your example doesn't work.这显然是一个非常有缺陷的 function 并且永远不应该使用,但说明了为什么您的示例不起作用。
Under the hood, what read
is doing is very similar to this strcpy
function: it is overwriting a lot of bytes in memory starting at the address pointed to by the fp
pointer.在幕后,
read
所做的与这个strcpy
function 非常相似:它从fp
指针指向的地址开始覆盖 memory 中的很多字节。 You are effectively losing your reference to the FILE *
pointer and the resources associated to it.您实际上失去了对
FILE *
指针和与之关联的资源的引用。
I'll bet that if you try to close(fp)
after that loop you'll get a segmentation fault (it's Undefined Behavior, but I'll bet anyway).我敢打赌,如果您在该循环之后尝试
close(fp)
,您会遇到分段错误(这是未定义的行为,但我还是打赌)。
The right way to do what you want is:做你想做的事情的正确方法是:
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.