encrypt.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. ** Copyright @ 2020 Joshua Branson <jbranso@dismail.de>
  3. **
  4. ** This program is free software; you can redistribute it and/or modify it
  5. ** under the terms of the GNU General Public License as published by
  6. ** the Free Software Foundation; either version 3 of the License, or (at
  7. ** your option) any later version.
  8. **
  9. ** It is distributed in the hope that it will be useful, but
  10. ** WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ** GNU General Public License for more details.
  13. **
  14. ** You should have received a copy of the GNU General Public License
  15. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <stdio.h>
  18. #include <ctype.h>
  19. #include <stdlib.h> //abs
  20. #include <string.h>
  21. #include <errno.h>
  22. FILE * maybe_open_file ()
  23. {
  24. extern char fileName [];
  25. extern char * program_invocation_short_name;
  26. FILE * stream;
  27. if (strlen (fileName) > 0)
  28. {
  29. if ((stream = fopen (fileName, "r")) == NULL)
  30. {
  31. fprintf (stderr, "%s: Couldn't open file %s; %s\n",
  32. program_invocation_short_name, fileName, strerror (errno));
  33. exit (EXIT_FAILURE);
  34. }
  35. else
  36. return stream;
  37. }
  38. else
  39. return stdin;
  40. }
  41. /* This function decrypts letters.
  42. print_shift('a', 1) -> 'b'
  43. print_shift('B', 1) -> 'C'
  44. */
  45. void print_shifted (int shift, int c)
  46. {
  47. unsigned int lower, upper; // upper is 'a' or 'A', and lower is 'z' or 'Z'
  48. if (isupper (c))
  49. {
  50. lower = 'A';
  51. upper = 'Z';
  52. }
  53. else
  54. {
  55. lower = 'a';
  56. upper = 'z';
  57. }
  58. // if we add the shift, and the resulting char is not a letter, then
  59. // we need to do tweak things.
  60. c += shift;
  61. if ( abs (c) > upper )
  62. c = lower + (c - (upper + 1));
  63. putchar (c);
  64. }
  65. void encrypt (int shift, FILE * stream)
  66. {
  67. char c; /* If I make this a char c, then 'z' + 7 = -128 */
  68. while ((c = getc(stream)) != EOF)
  69. //if the char is NOT a letter, then print it.
  70. (!(isalpha (c))) ? putchar(c) : print_shifted(shift, c);
  71. }