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?
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 5×5 array (a comment from you implies it is 10×2, 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
fpafter you’ve already read the data intoarrayis 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.