Skip to content

Instantly share code, notes, and snippets.

@brunofurmon
Last active September 16, 2020 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunofurmon/e5fc003bf84e0a051a0f to your computer and use it in GitHub Desktop.
Save brunofurmon/e5fc003bf84e0a051a0f to your computer and use it in GitHub Desktop.
This program implements a simple Cypher (Caesar's Cypher) on a text file. Ansi C
/* Implementa cifra de Caesar em arquivos de texto
* Uso: ./caesar <E/D> <CIFRA> <arquivoEntrada.txt> <arquivoSaida.txt>
* onde:
* 'E' soma a cada caracter o valor da cifra
* 'D' subtrai de cada caracter o valor da cifra
*
* Autor: Bruno Furtado Montes Oliveira
* github.com/brunofurmon
* skype: brunofurmon
* For an english explanation, get in contact ;)
*/
#include <stdio.h>
#include <stdlib.h>
/*Códigos de Erro*/
#define SUCCESS 0
#define INVALID_ARGS 1
#define INVALID_MODE 2
#define INVALID_CYPHER 3
#define INVALID_FILEIN 4
#define INVALID_FILEOUT 5
/*Constantes do programa*/
#define N_ARGS 5
#define ARG_MODE 1
#define ARG_CYPHER 2
#define ARG_FILEIN 3
#define ARG_FILEOUT 4
int main (int argc, char** argv){
/*Arquivo de entrada*/
FILE* fileIN;
/*Arquivo de saída*/
FILE* fileOUT;
/*Modo*/
char mode;
/*Cifra*/
int cypher;
/*Buffer de leitura*/
char buffer;
/*Buffer cifrado*/
char cBuffer;
if (argc != N_ARGS){
printf("./caesar <E/D> <CIFRA> <arquivoEntrada.txt> <arquivoSaida.txt>\n");
return INVALID_ARGS;
}
mode = *argv[ARG_MODE];
/*Teste de modo*/
if ((mode != 'E') && (mode != 'D')) {
printf("Modo inválido \"%c\". Deve ser (E)ncriptar ou (D)ecriptar\n", mode);
return INVALID_MODE;
}
/*Conversão de string para inteiro*/
cypher = atoi(argv[ARG_CYPHER]);
if (mode == 'D') {
cypher *= -1;
}
/*Abrir arquivo de entrada*/
/*Testar arquivo de entrada*/
if (!(fileIN = fopen(argv[ARG_FILEIN], "r"))) {
printf("Arquivo não encontrado ou permissões negadas para \"%s\"\n.",
argv[ARG_FILEIN]);
return INVALID_FILEIN;
}
/*Abrir arquivo de saída*/
/*Testar arquivo de saída*/
if (!(fileOUT = fopen(argv[ARG_FILEOUT], "w"))) {
printf("Arquivo não encontrado ou permissões negadas para \"%s\"\n.",
argv[ARG_FILEOUT]);
fclose(fileOUT);
return INVALID_FILEOUT;
}
/*Loop de escrita do arquivo de entrada*/
/*Lendo byte a byte*/
while (fread(&buffer, sizeof(char), 1, fileIN) == 1) {
/*printf("Lido: %c ", buffer);*/
cBuffer = buffer + cypher;
fwrite(&cBuffer, sizeof(char), 1, fileOUT);
}
fclose(fileIN);
fclose(fileOUT);
const char* modeName = (mode == 'D')? "Decriptação": "Encriptação";
printf("Programa executado no modo de %s com cifra %i.\n", modeName, cypher);
return SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment