从C中的文本文件移位密码中读取

时间:2016-11-09 17:01:00

标签: c

我正在使用Shift密码,我遇到加密问题。它没有错误或编译有问题,但在我运行它后,输出文件为空。我认为读取文件但未加密的out.txt文件为空。我没有解决它。谢谢。

int main
{

    file_in = fopen("/Users/mathmoiselle/Desktop/lucky.txt", "r");

    if( file_in == NULL )
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }

    file_out = fopen("/Users/mathmoiselle/Desktop/out.txt","r");

    return 0;
}

1 个答案:

答案 0 :(得分:1)

继续我的评论。您需要回滚file_in的文件指针,并且您的包含在顶部格式不正确。不确定这是否有所作为(初学者自己,但在阅读时肯定会突然出现):

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

int encode (int, int);

int encode(int ch, int key) {
    if (islower(ch)) {
        ch = (ch-'a' + key) % 26 + 'a';
        ch += (ch < 'a') ? 26 : 0;
    }
    else if (isupper(ch)) {
        ch = (ch-'A' + key) % 26 + 'A';
        ch += (ch < 'A') ? 26 : 0;
    }
    return ch;
}
int main (void)
{
    FILE *file_in;
    FILE *file_out;
    char ch;
    char text[300];
    int key;

    // gets(text);  // Removed in question
    file_in = fopen("shift_cipher.c", "r");


    if( file_in == NULL )
    {
        perror("Error while opening the file.\n");
        exit(EXIT_FAILURE);
    }
    printf("\n The contents of the file are : \n");

    while( ( ch = fgetc(file_in) ) != EOF )
    {
        printf("%c",ch);
    }

    rewind(file_in);

    // while (fgets(line, MAXLINE, f1)) {
    //     printf("%s", line);
    // }

    // gets(text);  // Removed in question
    file_out = fopen("out.txt","w");

    printf("\n Enter the alphabetic offset key you would like to use:");
    scanf("%d", &key);

    while( ( ch = fgetc(file_in) ) != EOF )
    {
        printf("%c", ch);
        ch=encode(ch, key);
        fprintf(file_out, "%c", ch);
    }
    printf("file has been encoded");
    fclose(file_out);
    fclose(file_in);

    return 0;
}