1

I've written a program to encrypt a given message by XOR. It works, but It doesn't end. Here is the code.(I have created 3 files):

encrypt.h :

void encrypt(char *message);

message_hider.c:

#include <stdio.h>
#include "encrypt.h"

int main() {
  char msg[80];

  while (fgets(msg, 80, stdin)){
    encrypt(msg);
    printf("%s", msg);
  }

  return 0;
}

encrypt.c :

#include "encrypt.h"

void encrypt(char *message) {
  while (*message) {
    *message++ ^= 0x1f;
  }
}

As I mentioned above, It works. but I can't stop it. When I pressed Ctrl+D to stop it (in cmd) It encrypts it also.(I need this code stop after it encrypt a message). Please explain me about this case.

4

5 回答 5

5

When I pressed Ctrl+D to stop it (in cmd)

If that's the cmd from Windows you probably want Ctrl+Z.

于 2012-08-17T07:55:37.457 回答
4

Ctrl-D is used for the console EOF on Unix systems.

Ctrl-Z is used for the console EOF on Windows systems.

于 2012-08-17T08:01:12.757 回答
2

isprint() can help:

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

void encrypt(char *message)
{
    while (*message) {
        *message = *message ^ 31;
        message++;
    }
}

int main(void)
{
    char msg[80];

    while (fgets(msg, 80, stdin) != NULL) {
        if (!isprint((unsigned char)*msg)) break;
        encrypt(msg);
        printf("%s", msg);
    }
    return 0;
}
于 2012-08-17T08:19:56.050 回答
1

Add an exit condition:

if( c < 0x20 ) break;

You may need to add other checks also to support backspace without encoding it...

http://www.asciitable.com/

于 2012-08-17T08:01:55.027 回答
0

Just run

  $> kill -l

To see the list of signals in Linux. You will not find SIGKILL (Ctrl + D) signal there :(

Ctrl + D is SIGKILL (0) signal in Linux which is not documented anywhere. Ctrl + Z is for Windows which tell EOF and we need to press "Enter" to close.

于 2012-08-17T09:39:55.797 回答