开发者

How to read a binary file and save it inside a pipe

开发者 https://www.devze.com 2023-02-03 01:52 出处:网络
I used the code below to open a binary file fp (the file contain a saved 2D array) and put it inside a pipe:

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 i开发者_运维技巧t 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?


The most sensible way to write the array to the pipe, as long as the size remains small, is to do:

int nw = 5 * 5 * sizeof(int);
if (write(fd[1], array, nw) != nw)
    err_exit("Failed to write to pipe");

(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 the close(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 into array 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):

enum { DIM_1 = 5, DIM_2 = 5 };
int array[DIM_1][DIM_2];

...data to load array...

int sum = 0;
for (int i = 0; i < DIM_1; i++)
{
    for (int j = 0; j < DIM_2; j++)
         sum += array[i][j];
}

It doesn't matter where the data came from, just so long as you actually initialized it.

0

精彩评论

暂无评论...
验证码 换一张
取 消