/* 
  Example of the popen/pclose command (process I/O).
  Get a list of files using the popen command.

  -MCW, Sept 2024
*/

#include <stdio.h>
#include <stdlib.h>     // defines "system", "exit"

#define BUFFER_SIZE 1024

int main (int argc, char *argv[]) {

  // myProcess is a stream that we will read from.
  // This is like reading input from the user, except that
  // the input is coming from a different "file".
  FILE *myProcess;
  // buffer is a place to store text. 
  // Instead of reading from the stream 1 char at a time, we 
  // read many of them, defined as BUFFER_SIZE above.
  char buffer[BUFFER_SIZE];
  int count = 0;

  printf("Here is a list of all files that end with .c\n");

  // List all files in the current dir that end with .c 
  // Open the stream
  myProcess = popen("ls *.c", "r");  // "r" for read
  // Always check to see if the command worked.
  if (myProcess == NULL) {
    // It did not work, so quit.
    printf("Error: ls *.c command failed\n");
    exit(1);
  }

  // Read up to BUFFER_SIZE-1 chars.
  fgets(buffer, BUFFER_SIZE, myProcess);
  // Check for end-of-file
  while (!feof(myProcess)) {
    count++;
    // Print it out
    // Notice that there is no \n since one is in the buffer
    printf("File %d is %s", count, buffer); 
    // get the next line
    fgets(buffer, BUFFER_SIZE, myProcess);
  }
  // Close the stream
  pclose(myProcess);


  return 0;
}
