如何读取二进制文件并将其保存在管道中
我使用下面的代码打开一个二进制文件 fp
(该文件包含保存的二维数组)并将其放入管道中:
if ((fp=fopen("file", "rb"))==NULL) {
printf("Cannot open file.\n");
}
if (fread(array, sizeof(int), 5*5, fp) != 5*5) {
if (feof(fp))
printf("Premature end of file.");
} else {
printf("File read error fread.");
}
这是将其放入管道中的代码吗?
close(fd[0]);
if ((ch=fgetc(fp))==EOF)
write(fd[1], &ch, 1 );
如果我想对数组求和,我该怎么做呢?
I used the code below to open a binary file fp
(the file contain a saved 2D array) and put it inside a pipe:
if ((fp=fopen("file", "rb"))==NULL) {
printf("Cannot open file.\n");
}
if (fread(array, sizeof(int), 5*5, fp) != 5*5) {
if (feof(fp))
printf("Premature end of file.");
} else {
printf("File read error fread.");
}
Is this the code to put it inside the pipe?
close(fd[0]);
if ((ch=fgetc(fp))==EOF)
write(fd[1], &ch, 1 );
If I want to make a sum of the array, how could I make it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要大小保持较小,将数组写入管道的最明智的方法是:(
其中 err_exit() 是一个将消息写入标准错误并退出的函数(或不返回。)
这假设你的数组是一个 5x5 数组(你的注释暗示它是 10x2,在这种情况下你的读取代码有重大问题)它假设管道中缓冲区的大小足够大。保存数据;如果不是,您的写入调用可能会阻塞。 SIGPIPE 信号,由于
close(fd[0]);
的缘故,可以一次写入一个字节 -
从 < 中一次读取一个字节的 性能并不理想。在将数据读入 array 后,执行 code>fp 并不完全明智 - 您最多只是读取不同的数据以写入管道,
这是对 2D 数组求和的正常方法 。 is (C99):
数据来自哪里并不重要,只要你实际初始化它即可。
The most sensible way to write the array to the pipe, as long as the size remains small, is to do:
(Where
err_exit()
is a function that writes a message to standard error and exits (or does not return.)This assumes that your array is a 5x5 array (a comment from you implies it is 10x2, in which case your reading code has major problems). It assumes that the size of the buffer in a pipe is big enough to hold the data; if it is not, your write call may block. It assumes that there is somewhere a process to read from the pipe; if this is the only process, the
write()
will trigger a SIGPIPE signal, killing your process, because of theclose(fd[0]);
.Writing one byte at a time is possible - it is not stellar for performance.
Reading one byte at a time from
fp
after you've already read the data intoarray
is not entirely sensible - you are at best reading different data for writing to the pipe.The normal way of summing a 2D array is (C99):
It doesn't matter where the data came from, just so long as you actually initialized it.