【问题标题】:Encrypt a message in C using file processing使用文件处理在 C 中加密消息
【发布时间】:2014-12-11 16:29:32
【问题描述】:

很高兴再次向您提问!

我想创建一个程序,它基本上读取一个名为 message.txt 的文件,该文件将包含一些带有消息的文本,比如说:“你好,我是一个程序”,然后对该消息进行加密并将其放入文件中称为 encryptMessage.txt,另外它会将用户使用的密钥保存在文件 key.txt 中。现在这就是我到目前为止所做的。我不知道如何让程序读取文件message.txt,将其显示到屏幕上,然后将其加密到文件中。有什么建议吗?谢谢!

我打算使用 fscanf,但我不能使用它,因为它是一行,而不仅仅是一个字符串。

如果可能,请自己编写代码,以便我可以将其与我目前所写的进行比较。我一直很感激您的反馈,谢谢!

#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100

int main(void)
{
    FILE *message;
    FILE *encryptMessage;
    FILE *key;

    message = fopen("message.txt", "r");
    encryptMessage = fopen("encryptMessage.txt", "w");
    key = fopen("key.txt", "w");

    if  ((encryptMessage == NULL) || (encryptMessage == NULL) || (encryptMessage == NULL))
    {
            printf("Error reading file!!!\n");
            return 1;
    }

    int userKey;
    char sentence[MAXSIZE];
    char q[MAXSIZE];
    int i = 0;

    printf("Input the text that you want to encrypt:\n> "); // These two lines are a test to see if I was able to encrypt the message, but this is not necessary. It should directly read the file called message.txt.
    fgets(sentence, 99, stdin);

   // printf("\nThe string that you wrote is:\n%s\n\n", sentence);

    printf("Input the key:\n");
    scanf("%d", &userKey);
    fprintf(key, "%d", userKey);

    //printf("\nThe key that you selected is: %d\n\n", userKey);

    for(i = 0; sentence[i] != '\0'; ++i)
    {
        if( ( isupper(sentence[i]) ) || ( islower(sentence[i]) ) )
        {
            q[i] = sentence[i] + (char)userKey;
        }
        else
        {
            q[i] = (sentence[i]);
        }
    }

    q[i] = '\0';
    printf("%s", q);
    fprintf(encryptMessage, "%s", q);

    fclose(encryptMessage);

    return 0;
}

【问题讨论】:

标签: c string file encryption


【解决方案1】:

要从message.txt 读取一行,您需要使用fgets 函数。

fgets(sentence, 99, stdin);

上面的fgets(您的代码中有)从通常是键盘的stdin 中读取。要使其从文本文件中读取,请使用

fgets(sentence, MAX_SIZE, message);

还要注意第二个参数的变化。如果要显示扫描的内容,请取消注释代码中的以下行

//printf("\nThe string that you wrote is:\n%s\n\n", sentence);

不要忘记在使用后关闭(使用fclose)所有您打开(使用fopen)的FILE指针。

【讨论】:

  • 这太容易了,在你告诉我之前我就想通了。我只是尝试更改它并且它起作用了,令人惊讶的是哈哈哈。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 2022-01-28
  • 1970-01-01
相关资源
最近更新 更多