Advertisement
NickAndNick

Файлы, строки, числа

Apr 10th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <locale.h>
  5. #include <limits.h>
  6. #include <string.h>
  7.  
  8. #define MAX_SIZE 0x7fff
  9.  
  10. size_t create(const char *);
  11. int * vector(const size_t);
  12. void show(int *, const size_t);
  13. void max_elements(const char *, int *);
  14.  
  15. int main() {
  16.     char filename[] = "numbers.txt";
  17.     size_t size;
  18.     int * v = NULL;
  19.  
  20.     if (size = create(filename)) {
  21.         setlocale(LC_CTYPE, "Russian_Russia.1251");
  22.         if (v = vector(size)) {
  23.             max_elements(filename, v);
  24.             show(v, size);
  25.             free(v);
  26.         }
  27.     }
  28.  
  29.     getchar();
  30.     return 0;
  31. }
  32.  
  33. void max_elements(const char * _fn, int * _v) {
  34.     FILE * stream;
  35.     int max, e;
  36.     unsigned n = 0;
  37.     char buff[MAX_SIZE];
  38.     char * token = NULL;
  39.  
  40.     if (fopen_s(&stream, _fn, "r")) printf("\a Невозможно открыть файл!\n");
  41.     else
  42.         while (!feof(stream)) {
  43.             max = INT_MIN;
  44.             fgets(buff, MAX_SIZE, stream);
  45.             token = strtok(buff, " ");
  46.  
  47.             while (token) {
  48.                 e = atoi(token);
  49.                 if (max < e) max = e;
  50.                 token = strtok(NULL, " ");
  51.             }
  52.  
  53.             _v[n++] = max;
  54.         }
  55.  
  56.     if (stream) if (fclose(stream)) printf("\a Невозможно закрыть файл!\n");
  57. }
  58.  
  59. void show(int * _v, const size_t _sz) {
  60.     unsigned n = 0;
  61.     do printf("%3i", _v[n]); while (++n < _sz);
  62.     printf("\n");
  63. }
  64.  
  65. int * vector(const size_t _sz) { return (int *)calloc(_sz, sizeof(int)); }
  66.  
  67. size_t create(const char * _fn) {
  68.     FILE * stream;
  69.     size_t rows = 0, cols;
  70.     unsigned r, c;
  71.     int e;
  72.  
  73.     if (fopen_s(&stream, _fn, "w")) printf("\a Невозможно создать файл!\n");
  74.     else {
  75.         srand((unsigned)time(NULL));
  76.         rows = 10 + rand() % 11;
  77.  
  78.         for (r = 0; r < rows; r++) {
  79.             cols = 16 + rand() % 17;
  80.  
  81.             for (c = 0; c < cols; c++) {
  82.                 e = 1 + rand() % 99;
  83.                 fprintf(stream, "%d", e);
  84.                 if (c < cols - 1) fprintf(stream, " ");
  85.             }
  86.  
  87.             if (r < rows - 1) fprintf(stream, "%c", '\n');
  88.         }
  89.  
  90.         if (stream) if (fclose(stream)) printf("\a Невозможно закрыть файл!\n");
  91.     }
  92.     return rows;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement