Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define BUFFER_SIZE 1024 * 16
  6.  
  7. int main(int argc, char *argv[]) {
  8.     if(argc == 1) {
  9.         fprintf(stderr, "Chybi cesta ke vstupnimu a vystupnimu souboru.");
  10.         exit(1);
  11.     } else if(argc == 2) {
  12.         fprintf(stderr, "Chybi cesta k vystupnimu souboru.");
  13.         exit(1);
  14.     }
  15.  
  16.     FILE* input = fopen(argv[1], "r");
  17.     FILE *output = fopen(argv[2], "w");
  18.     char line[BUFFER_SIZE];
  19.     int y = -1;
  20.     int width;
  21.     int height;
  22.     int **arr;
  23.  
  24.     if (input == NULL)
  25.     {
  26.         fprintf(stderr, "Vstupni soubor \"%s\" neexistuje", argv[1]);
  27.         exit(1);
  28.     }
  29.  
  30.     while (fgets(line, BUFFER_SIZE, input))
  31.     {
  32.         char* tmp = strdup(line);
  33.         int x = 0;
  34.         const char* tok;
  35.  
  36.         for (tok = strtok(line, " ");
  37.              tok && *tok;
  38.              tok = strtok(NULL, " \n"))
  39.         {
  40.             if(y == -1) {
  41.                 if(x == 0) {
  42.                     width = strtol(tok, NULL, 10);
  43.                 } else if(x == 1) {
  44.                     height = strtol(tok, NULL, 10);
  45.  
  46.                     arr = (int **)malloc(height * sizeof(int *));
  47.                     for (int i=0; i<height; i++)
  48.                         arr[i] = (int *)malloc(width * sizeof(int));
  49.                 }
  50.             }
  51.             //printf("%d ", strtol(tok, NULL, 10));
  52.             if(y != -1) {
  53.                 arr[x][y] = strtol(tok, NULL, 10);
  54.             }
  55.             x++;
  56.         }
  57.  
  58.         free(tmp);
  59.         y++;
  60.     }
  61.  
  62.     for (int i = 0; i <  height; i++) {
  63.         for (int j = 0; j < width; j++) {
  64.             if(j == 0) {
  65.                 fprintf(output, "%d", arr[i][j]);
  66.             } else if(j == width - 1) {
  67.                 fprintf(output, " %d\n", arr[i][j]);
  68.             } else {
  69.                 fprintf(output, " %d", arr[i][j]);
  70.             }
  71.         }
  72.     }
  73.  
  74.     fclose(input);
  75.     fclose(output);
  76.  
  77.     for (int i = 0; i < height; i++)
  78.     {
  79.         int* currentIntPtr = arr[i];
  80.         free(currentIntPtr);
  81.     }
  82.     free(arr);
  83.  
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement