Question

I write a program for encrypting.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <readline/readline.h>

int main(void) {
    char * plain;
    char letter;
    int value;
    int index;

    plain = readline("Please input your plain text: ");
    printf("Please input your key (included negatives): ");
    scanf("%i", &value);

    for (index = 0; index < strlen(plain); index++) {
        letter = plain[index];

        if (letter >= 'A' && letter <= 'Z') {
            fprintf(stderr, "%c", (letter - 'A' + value) % 26 + 'A');
        }

        else if (letter >= 'a' && letter <= 'z') {
            fprintf(stderr, "%c", (letter - 'a' + value) % 26 + 'a');
        }
        else {
            fprintf(stderr, "%c", letter);
        }
    }
    fprintf(stderr, "\n");
    free(plain);
}

And I did some benchmarks:

biergaizi@localhost ~/learning_c/test $ time ./caesar_readline < lots_of_letters 2> c_readline_result > /dev/null

real    2m31.212s
user    2m30.776s
sys     0m0.165s

The program spend too much time to read the text from standard input. If I remove > /dev/null, I can see the program is reading from standard input, too slow!

I also wrote version without GNU Readline, it is very fast.

Why? And How can I solve it?

Was it helpful?

Solution

Because the feature it provides.

provides a set of functions for use by applications that allow users to edit command lines as they are typed in. Both Emacs and vi editing modes are available.

I think you can just use open function

if (!strcmp(*argv, "-"))
  fd = fileno(stdin);
else fd = open(*argv, O_RDONLY|O_NONBLOCK, 0);

and provide - as filename if you want read from stdin

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top