0

I have a text file and I should display its content using pipe in a C program. I have made something like this but isn't exactly what I need.

#include <unistd.h>

#define MSGSIZE 16

char msg1 = "hello, world #1"; char msg2 = "hello, world #2"; char *msg3 = "hello, world #3";

int main() { char inbuf[MSGSIZE];

int p[2], i;

if (pipe(p) < 0) exit(1);

/* continued / / write pipe */

write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE);

for (i = 0; i < 3; i++) { /* read pipe */ read(p[0], inbuf, MSGSIZE); printf("% s\n", inbuf); } return 0; }

Here I gave the messages that I want to display. I really do not know how to do it for a file.

Kusalananda
  • 333,661
Vv_Ff
  • 1
  • 1
    To read from a file via a pipe, something must read from the file the traditional way (i.e., open() followed by read() system calls), and write that into the pipe. The pipe system call is normally used before forking, after which parent and child use the two sides of the pipe. I see nothing like that in your program. – berndbausch May 17 '21 at 16:03
  • This isn't exactly the same, but it might help: https://unix.stackexchange.com/a/633624/90691 – Andy Dalton May 19 '21 at 22:44

1 Answers1

0
#include <unistd.h>
#include <fcntl.h>

#define MSGSIZE 1024

int main() {
  char inbuf[MSGSIZE];

  int n, fd, p[2], i;

  if ((fd=open("/etc/passwd", O_RDONLY))<0)
    exit(2);
  if (pipe(p) < 0)
    exit(1);

  /* continued */
  /* write pipe */

  while ((n=read(fd,inbuf,MSGSIZE))>0)
      write(p[1], inbuf, n);
  close(p[1]);

  while ((n=read(p[0],inbuf,MSGSIZE))>0)
    write(1,inbuf,n);

  exit(0);
}

This does the job. I am not sure what's the point of this exercise, though.

berndbausch
  • 3,557