Skip to content

Instantly share code, notes, and snippets.

@Costava
Created April 11, 2021 17:22
Show Gist options
  • Save Costava/2393d38bb4c4aed3b4d62cd40eb4251e to your computer and use it in GitHub Desktop.
Save Costava/2393d38bb4c4aed3b4d62cd40eb4251e to your computer and use it in GitHub Desktop.
Print the given string and all of its shifted variations
/*
* caesarshiftall.c
*
* Print the given string and all of its shifted variations.
* Print a newline after each.
* Return 0 on success.
* Return non-zero on failure. See ERROR_ defines.
*
* Example compilation:
* gcc caesarshiftall.c -o caesarshiftall -std=c89 -Wall -Wextra -Wconversion
*
* Info on Caesar shift: https://en.wikipedia.org/wiki/Caesar_cipher
*
* License:
*
* BSD Zero Clause License
*
* Copyright (C) 2021 by Costava
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
/* Wrong number of args given to program */
#define ERROR_NUM_ARGS 1
/* fputc errored */
#define ERROR_FPUTC 2
/* fputs errored */
#define ERROR_FPUTS 3
/* fputc but exit with code ERROR_FPUTC if error. */
void checked_fputc(const char ch, FILE *const stream) {
if (fputc(ch, stream) == EOF) {
exit(ERROR_FPUTC);
}
}
/* fputs but exit with code ERROR_FPUTS if error. */
void checked_fputs(const char *str, FILE *stream) {
if (fputs(str, stream) == EOF) {
exit(ERROR_FPUTS);
}
}
/*
* If the given character is an uppercase or lowercase letter,
* shift it forward in the alphabet by 1.
* Z becomes A. z becomes a.
* Else return the given character.
*/
char shift(const char c) {
if (c >= 'A' && c <= 'Z') {
return (char)('A' + ((c - 'A' + 1) % 26));
}
else if (c >= 'a' && c <= 'z') {
return (char)('a' + ((c - 'a' + 1) % 26));
}
return c;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
checked_fputs("USAGE: ./caesarshiftall <string>\n", stderr);
return ERROR_NUM_ARGS;
}
char *const target = argv[1];
/* Print given string */
checked_fputs(target, stdout);
checked_fputc('\n', stdout);
/* Print all shifts of given string */
int i;
for (i = 0; i < 25; i += 1) {
/* Shift each letter */
char *c = target;
while (*c != '\0') {
*c = shift(*c);
c += 1;
}
checked_fputs(target, stdout);
checked_fputc('\n', stdout);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment