1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include <stdio.h> #include <stdlib.h> #include <string.h>
void run_program(const char *program, const char *input, char **output) { size_t buffer_size = 1024; size_t output_size = buffer_size; *output = (char *)malloc(output_size); if (*output == NULL) { perror("malloc failed"); exit(EXIT_FAILURE); }
char command[buffer_size]; snprintf(command, sizeof(command), "echo %s | %s", input, program); FILE *fp = popen(command, "r"); if (fp == NULL) { perror("open filed failed"); exit(EXIT_FAILURE); }
size_t len = 0; while (fgets(*output + len, buffer_size, fp) != NULL) { len += strlen(*output + len); if (len + buffer_size > output_size) { output_size *= 2; *output = (char *)realloc(*output, output_size); if (*output == NULL) { perror("realloc failed"); exit(EXIT_FAILURE); } } } pclose(fp); }
int main() { FILE *input_file = fopen("input.txt", "r"); if (input_file == NULL) { perror("fopen input.txt failed"); return EXIT_FAILURE; }
fseek(input_file, 0, SEEK_END); long input_size = ftell(input_file); fseek(input_file, 0, SEEK_SET);
char *input = (char *)malloc(input_size + 1); if (input == NULL) { perror("malloc failed"); return EXIT_FAILURE; }
fread(input, 1, input_size, input_file); input[input_size] = '\0'; fclose(input_file);
char *output1 = NULL; char *output2 = NULL;
run_program("./program1", input, &output1); run_program("./program2", input, &output2);
FILE *output_file = fopen("output.txt", "w"); if (output_file == NULL) { perror("fopen output.txt failed"); return EXIT_FAILURE; }
if (strcmp(output1, output2) == 0) { fprintf(output_file, "Outputs are identical.\n"); } else { fprintf(output_file, "Outputs differ.\n"); fprintf(output_file, "Output from program 1:\n%s\n", output1); fprintf(output_file, "Output from program 2:\n%s\n", output2); }
fclose(output_file); free(input); free(output1); free(output2);
return 0; }
|