[c] codage/décodage rot13

Description

Code/décode tous les arguments passés en paramètre ou lit depuis l'entrée standard si aucun argument n'est passé :

$ ./rot13 salut vous !
fnyhg ibhf !

$ cat FICHIER | ./rot13
blabla
...

Contient un fichier makefile, donc pour installer rien de plus simple :
# make
# make install
#make clean

Source / Exemple :


/* main.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define BUFFER_SZ  256
/*#define ORDERED_LETTERS */

enum { SUCCESS = 0, ERROR = 1, MEM_ERROR = 2 };

void show_usage(char* prg);
void rot13(char * str);

int main(int argc, char ** argv)
{
    
    if( argc == 2 && strcmp(argv[1], "--help") == 0 )
    { /* help */
        show_usage(argv[0]);
        return SUCCESS;
    }
    
    if(argc == 1)
    { /* on lit l'entrée standard */
    
        char buff[BUFFER_SZ];
        
        while( fgets(buff, BUFFER_SZ, stdin) != NULL )
        {
            rot13(buff);
            fputs(buff, stdout);
        }
        
        fflush(stdout);
            
        return SUCCESS;
    }
    
    if(argc >= 2)
    { /* on concatène tous les arguments */
    
        char * str;
        int i;
        int needed = 0;
        
        for(i = 1; i < argc; ++i)
            needed += strlen(argv[i]) + 1;

        if( (str = calloc(needed, 1) ) == NULL )
        {
            fprintf(stderr, "%s: Error: Unable to allocate memory\n", argv[0]);
            return MEM_ERROR;
        }
        
        strcpy(str, argv[1]);
        for(i = 2; i < argc; ++i)
        {
            strcat(str, " ");
            strcat(str, argv[i]);
        }
        
        rot13(str);
        fputs(str, stdout);
        fputc('\n', stdout);
        fflush(stdout);
        
        free(str);
        
        return SUCCESS;
    }
    
    return ERROR;
}

void rot13(char * str)
{ /* code/decode une chaine en rot13 indépendemment
     du code ASCII des caratères */
    static char const * const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLM"
                                        "abcdefghijklmnopqrstuvwxyzabcdefghijklm";
    int i = 0;
        
    while( str[i] != 0 )
    {
        char * found = strchr( letters, str[i] );
        if( found != NULL )
            str[i] = *(found + 13);

        ++i;
    }
}

void show_usage(char* prg)
{
    printf("Usage: %s [--help] [string [string2 [string3 ...]]]\n", prg);
    printf("\tstring\tString to encode/decode\n");
    printf("\t--help\tShow help\n");
    printf("If string argument is not provided, read string from standard input\n");
}

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.