Advertisement
STANAANDREY

histogram

Jan 9th, 2023
1,024
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4. #define OFILE_NAME "histo.txt"
  5. #define SIGMA 'z' - 'a' + 1
  6. int freqLow[SIGMA], freqUp[SIGMA], total;
  7.  
  8. FILE *safeOpenFile(const char *const path, const char *const mode) {
  9.     FILE *file = NULL;
  10.     file = fopen(path, mode);
  11.     if (file == NULL) {
  12.         perror("opening error!");
  13.         exit(EXIT_FAILURE);
  14.     }
  15.     return file;
  16. }
  17.  
  18. void safeCloseFile(FILE *file) {
  19.     if (fclose(file) == EOF) {
  20.         perror(NULL);
  21.     }
  22. }
  23.  
  24. void getFreq(const char *const path) {
  25.     FILE *file = safeOpenFile(path, "r");
  26.     for (char ch; (ch = fgetc(file)) != EOF;) {
  27.         if (!isalpha(ch)) {
  28.             continue;
  29.         }
  30.         if (islower(ch)) {
  31.             freqLow[ch - 'a']++;
  32.         } else {
  33.             freqUp[ch - 'A']++;
  34.         }
  35.         total++;
  36.     }
  37.     safeCloseFile(file);
  38. }
  39.  
  40. void writeHisto(const char *const path) {
  41.     FILE *file = safeOpenFile(path, "w");
  42.     for (char ch = 'a'; ch <= 'z'; ch++) {
  43.         if (!freqLow[ch - 'a']) {
  44.             continue;
  45.         }
  46.         fprintf(file, "%c - %g%%\n", ch, 100.0 * freqLow[ch - 'a'] / total);
  47.     }
  48.     for (char ch = 'A'; ch <= 'Z'; ch++) {
  49.         if (!freqUp[ch - 'A']) {
  50.             continue;
  51.         }
  52.         fprintf(file, "%c - %g%%\n", ch, 100.0 * freqUp[ch - 'A'] / total);
  53.     }
  54.     safeCloseFile(file);
  55. }
  56.  
  57. int main(int argc, char **argv) {
  58.     if (argc == 1) {
  59.         fprintf(stderr, "ONE MORE ARG NEEDED!\n");
  60.         exit(-1);
  61.     }
  62.     getFreq(argv[1]);
  63.     writeHisto(OFILE_NAME);
  64.     return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement