CS3502/assignment2/part1/producer.c
2025-10-06 23:27:46 -04:00

44 lines
975 B
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
int main(int argc, char *argv[]) {
FILE *input = stdin;
int buffer_size = 4096;
// Parse command line arguments
// -f filename (optional)
// b buffer_size (optional)
char opt;
while ((opt = getopt(argc, argv, "f:b:")) != -1) {
switch (opt) {
case 'f':
input = fopen(optarg, "r");
if (input == NULL) {
fprintf(stderr, "Error: Could not open input file\n");
return EXIT_FAILURE;
}
break;
case 'b':
buffer_size = atoi(optarg); break;
default:
printf("Usage: %s [-f filename] [-b buffer_size]\n", argv[0]);
return 1;
}
}
// Allocate buffer
char *buffer = malloc(buffer_size);
// Read from input and write to stdout
while (fgets(buffer, buffer_size, input) != NULL) {
fwrite(buffer, sizeof(char), strlen(buffer), stdout);
}
// Cleanup
free(buffer);
return 0;
}