Advertisement
999ms

Untitled

Oct 14th, 2020
2,256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. void cpy(char** d, char** s) {
  7.     int n = strlen(*s);
  8.     (*d) = (char*)malloc(sizeof(char) * n);
  9.     for (int i = 0; i < n; i++) {
  10.         (*d)[i] = (*s)[i];
  11.     }
  12. }
  13.  
  14. char* get_command(char* commands[], int n) {
  15.     int size = n;
  16.     for (int i = 0; i < n; i++) {
  17.         size += strlen(commands[i]);
  18.     }
  19.     char* result = (char*)malloc(sizeof(char) * size);
  20.     int itr = 0;
  21.     for (int i = 0; i < n; i++) {
  22.         int cur_len = strlen(commands[i]);
  23.         for (int j = 0; j < cur_len; j++) {
  24.             result[itr++] = commands[i][j];
  25.         }
  26.         result[itr++] = ' ';
  27.     }
  28.     result[itr - 1] = '\0';
  29.     return result;
  30. }
  31.  
  32.  
  33. FILE* execute(char* commands[], int n, const char* type) {
  34.     FILE* stream = popen(get_command(commands, n), type);
  35.     return stream;
  36. }
  37.  
  38.  
  39. int main(int argc, char* argv[]) {
  40.     if (argc < 3) {
  41.         printf("WRONG INPUT\n");
  42.         return 1;
  43.     }
  44.    
  45.     int size1 = 1;
  46.     char border = 0;
  47.     int size2 = 1;
  48.     for (int i = 2; i < argc; i++) {
  49.         if (argv[i][0] != '-') {
  50.             border = 1;
  51.         } else if (border) {
  52.             size2++;
  53.         } else {
  54.             size1++;
  55.         }
  56.     }
  57.    
  58.     char* argv1[size1 + 1];
  59.     argv1[size1] = NULL;
  60.  
  61.     char* argv2[size2 + 1];
  62.     argv2[size2] = NULL;
  63.    
  64.     for (int i = 0; i < size1; i++) {
  65.         cpy(&argv1[i], &argv[i + 1]);
  66.     }
  67.    
  68.     for (int i = 0; i < size2; i++) {
  69.         cpy(&argv2[i], &argv[i + 1 + size1]);
  70.     }
  71.    
  72.     FILE* first_stream = execute(argv1, size1, "r");
  73.     FILE* second_stream = execute(argv2, size2, "w");
  74.    
  75.     const int BUFFER_SIZE = 1 << 10;
  76.     char BUFFER[BUFFER_SIZE];
  77.  
  78.     while (fgets(BUFFER, sizeof(BUFFER), first_stream)) {
  79.         fprintf(second_stream, "%s", BUFFER);
  80.     }
  81.    
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement