【发布时间】: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;
}
【问题讨论】:
-
回答“如何阅读整行”的问题:见question & answer。
标签: c string file encryption