パイプを使用してファイルの内容を表示するには?

パイプを使用してファイルの内容を表示するには?

テキストファイルがあり、Cプログラムでパイプを使用してその内容を表示する必要があります。似たようなものを作りましたが、必ずしも必要ではありません。

#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;
}

ここに私が表示したいメッセージを伝えます。ファイルでこれを行う方法がわかりません。

ベストアンサー1

#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);
}

これで作業が完了します。しかし、この練習のポイントが何であるかよくわかりません。

おすすめ記事